Intent

"Ensure a lass only has one instance, and provide a global point of access to it."

Motivation

The main aim of this design pattern is to create a class that only ever has one instance and ensure that there is a global point of access to this one instance. To give an example we can think about a simple game of Pong. In this game there will be only one playable paddle, with the other being controlled by AI. Therefore, it makes sense to use the singleton pattern here as there will only ever be one playable paddle.

UML Diagram:

When to Use?

The singleton design pattern is intended for use when there must be exactly one instance of a class and it must be accessible to clients from a well-known access point. Also when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Implementation Example

Singleton Class:

public class Singleton {

	private static Singleton uniqueInstance = null;

        // having a private constructor ensures that
        // we cannot instantiate more than one instance
        // of our singleton class.
	private Singleton(){ }

	public static Singleton getInstance(){

		if(uniqueInstance == null)
		{
			// Lazy instantiation
			uniqueInstance = new Singleton();
		}

		return uniqueInstance;

	}

	public String printInstance(){
		if(uniqueInstance == null){
			System.out.println("Not instantiated");
		}
		return "Instantiated";
	}

}

Client Class:

public class Client {

	public static void main(String args[]){

		Singleton unique = Singleton.getInstance();

		System.out.println(System.identityHashCode(unique));

		System.out.println(unique.printInstance());

	}

}