Friday, September 23, 2011

Singleton pattern


Sometimes it’s important for classes to have exactly one instance.
For example: Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager.

In such scenario Singleton Design Pattern comes to help.

Singleton pattern ensures a class only has one instance, and provides a global point of access to it.

Implementing Singleton

To implement singleton we need do following two things.
1.    Ensure a class only has one instance:
 This can be achieved by making constructor of a class private ( or protected: In case you want to extend this class.).
2.    Provides a global point of access to instance:
This can be achieved by keeping static reference to unique instance and having method to get that instance.


Java Implementation of Singleton:
public class Singleton {

// Static variable to hold unique instance.
private static Singleton uniqueInstance=null; 

// private constructor ensures that only Singleton class can access it.
   private Singleton(){}

// Method makes sure only one instance of Singleton is accessible globally.
  public static Singleton getInstance(){

     if(uniqueInstance==null){

       uniqueInstance= new Singleton();

     }

     return uniqueInstance;
 
  }

}
Now to get instance of Singleton class other classes will have to use getInstance() method.
For example:

 public static void main(String[] args) {
  // Creating Singleton instance
  Singleton s1 = Singleton.getInstance();
  .
  .
  Singleton s2 = Singleton.getInstance();
 }

When the getInstance() is called for first time value of uniqueInstance will be null and hence it will create new Singleton instance and return it.

When we call getInstance() method again uniqueInstance will be having the instance of Singleton and that instance will be returned. This will ensure that there is always unique instance of Singleton class and it's global point of access is getInstance() method.


Making it Thread safe:

In multithreading environment getInstance() may get called by multiple threads simultaneously, resulting into multiple instances of Singleton.
In such environment we should make getInstance() method thread safe by making it synchronized


public static synchronized Singleton getInstance(){

           if(uniqueInstance==null){
                uniqueInstance= new Singleton();
           }
           return uniqueInstance;
    }

3 comments:

नेहा said...

:) thanks for this , this is actually useful concept which should be clear... cheers!!!

Shraddha Jantre said...

Thanks for sharing .. :)

Prajakta said...

Nice article Dipesh. Very helpful.