The singleton pattern ensures that only one instance of an object can be instantiated. The code snippet (from tutorialspoint) below is an example of a singleton pattern.
public class Singleton {
private static Singleton singleton = new Singleton();
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton() { }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
First we notice that the Singleton
class is instanitated and stored in a static variable. As static variables share the same copy of the variable across all objects of the same type, so we ensure that the same object is persisted across all objects.
private static Singleton singleton = new Singleton();
Since the constructor is private, the only way to instantiate te Singleton
object is to call the static getInstance
method.
Singleton tmp = Singleton.getInstance( );