As the name suggest, Singleton Pattern restricts to the creation of one and only one object of a class. This is very useful whenever we want to restrict the creation of an object to single instance. This is very small and sweet type pattern that is used in many cases.
Let's take an example and see how it is used in the code
public class SingleObject { private static SingleObject singleObject; private SingleObject() { } public static SingleObject createInstance() { if (singleObject == null) { singleObject = new SingleObject(); } return singleObject; } }
Line by line explanation
Line 2: creates private instance of the class
Line 4: constructor is private, so that no outer class can create object of this class
Line 7: creating a static method to get an instance of the class. We have defined method as static so that we don't need to create a object to call this method. Since it is static we can call this method by name of the class i.e. SingleObject.createInstance().
Line 8: if object is null then we will create an object of the class else we will return the previous one.
Now, this type of initialization of class is known as the classic style for Singleton.
Here, we can say that this may fail i.e. single object concept, in the multi-threaded environment. For this, we make the method synchronized. This will change something like
public static synchronize createInstance(){
Some of you think that it will be overhead as it will take more memory and so. But does it really affect it, because this will call only once at the time of creation of the object and not always.
This type of initialization of class is known as the thread-safe style for Singleton.
This type of initialization of class is known as the thread-safe style for Singleton.
We can also make the object early by changing the line no 2
private static SingleObject singleObject = new SingleObject();
This is called eager initialization of the object. In this case, object is already created and whenever thread tries to call it will simply return the object. It all depends on what conditions are you building the class or calling it.
Hope everything is clear :).
Comments
Post a Comment