Singleton Design Pattern

Singleton Design Pattern belong to creational design pattern family and singleton design pattern is used when there is a need of only one instance of class in one container. Like one organization can have only one CEO in company. The singleton pattern is one of the simplest design patterns. It contains only one class which is responsible to instantiate itself and it make sure it creates not more than one instance and at the same time it make sure that there is only one way to access that instance.

To make any class a Singleton class, it involves a static member in the “Singleton” class, a private constructor and a static public method that returns a reference to the static member.

i.e.

class Singleton { 
      private static Singleton instance; 
      private Singleton() { 
              ... 
      } 
      public static synchronized Singleton getInstance(){ 
             if (instance == null) {
                    instance = new Singleton(); 
             }
             return instance; 
      } 
}

So the getInstance() method makes sure that only one instance of Singleton class exist and if one calls getInstance() method twice, we have if condition to check whether instance already exist or not.

But how will you get instance of Singleton class. Like below…

Singleton.getInstance().doSomething();

Following are the common use cases where Singleton class can be used

  • Logger class,
  • Configuration Class,
  • Classes those are responsible to load prop file in application.

 

Hope this clears your doubt!!

 


One thought on “Singleton Design Pattern

Comments are closed.