Skip to main content

Posts

Showing posts from October, 2017

Ways to define Singleton Classes

Singleton classes comes under "Creational design pattern", Singleton pattern restricts from creating multiple instances of the class,and ensure that only one object should be available in the JVM, there are different ways to implement singleton classes as below :- Ways to define Singleton classes :- 1. By defining the singleton class object as static final variable, this is known as early initialization of singleton object. public class SingletoneClassExample{ Private static final instance = new SingletoneClassExample(); // Define private constructor to avoid other classes from creating instance private SingletoneClassExample(){ } public static SingletoneClassExample getInstance(){         return instance;   } } By creating singleton class using above method the class object will be created at class loading itself, so if application is not using this class still the object will be created. 2. Define singleton class object on method call public class SingletoneCl