Singleton Pattern in Java

The Singleton pattern ensures that a class has only one instance, and provides a global point of reference to that instance. 



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.


Singleton Example:
public class SingletonPattern{
  private static SingletonPattern instance;
  private SingletonPattern(){}
public static synchronized SingletonPattern getInstance(){
  if (instance == null)
  {
  instance = new SingletonPattern();
  }
  return instance;
  }
public static void main(String arg[]){
  System.out.println("The output of two instance:");
  SingletonPattern sp=new SingletonPattern();
  System.out.println("First Instance: "+sp.getInstance());
  sp=new SingletonPattern();
  System.out.println("Second Instance:"+sp.getInstance());
  }
}




Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email