Design Patterns

Singleton Pattern (GOF - Creational)

Singleton pattern is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate across the system. It ensures only one instance of class is existing and provides a global point of access to the object.

Singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist. If an instance already exists, it simply returns a reference to that object.



Class Diagram





Singleton Class

public class Singleton {

	private static Singleton mySingleton = null;
	
	private Singleton () {     //constructor
	
	}
	
	public static Singleton getInstance() {
		
		if(mySingleton == null)
			mySingleton = new Singleton();
		
		return mySingleton;
	}
}

In any class to use the above singleton class:

Singleton singletonInstance = Singleton.getInstance();

The process how Singleton class is instantiated, is called lazy instantiation.