In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.
public class SingletonClass { private static SingletonClass instance = null; protected SingletonClass() { // can not be instantiated. } public static SingletonClass getInstance() { if(instance == null) { instance = new SingletonClass(); } return instance; } }
In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.
public class SingletonInstantiator { public SingletonInstantiator() { SingletonClass instance = SingletonClass.getInstance(); SingletonClass anotherInstance = new SingletonClass(); ... } }
In snippet above anotherInstance is created which is a perfectly legal statement as both the classes exist in the same package in this case 'default', as it is not required by an instantiator class to extend SingletonClass to access the protected constructor within the same package.So to avoid even such scenario, the constructor could be made private.
4 comments :
This is good
But i want some information which situation we can use singleton in cloning
The above code was the common implementation but there will be different implementation in case of cloning and multi-threaded environment. Refer to following link: https://javadevelopershelp.blogspot.com/2009/02/singleton-pattern-in-java.html
Aniket:
Thanks for sharing the information.
The constructor for the singleton class should not be protected but private.
Post a Comment