Singleton Pattern

The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

 

Intent

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.

 

 

Implementation

The implementation involves a static member in the “Singleton” class, a private constructor and a static public method that returns a reference to the static member.

singleton_implementation_-_uml_class_diagram

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.

 

class Singleton
{
	private static Singleton instance;
	private Singleton()
	{
		...
	}

	public static synchronized Singleton getInstance()
	{
		if (instance == null)
			instance = new Singleton();

		return instance;
	}
	...
	public void doSomething()
	{
		...	
	}
}

You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.

The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:

 

Singleton.getInstance().doSomething();
Advertisements