Friday, January 25, 2013

Singleton Design Pattern - Java




There may be situations that we need exactly one instance of a class to perform some functionalities. Singleton design pattern ensures that only one instance of a class is created and provides a global point of access to the object.


Public class MySingleton(){
     private static MySingleton singletonInstance;

     private MySingleton(){
     
     }

     public static MySingleton getSigleton(){
         if(singletonInstance = null)
             singletonInstance = new MySingleton()
         return singletonInstance;
     }
}

If we make the constructor of MySingleton class private, The outside classes can't create instances of MySingleton class. We can create instances only within MySingleton class. Therefore, public static getter method is created to give the instance to outside.


In the situations of using multi threading, getter method has to be put as synchronized because if two threads may access the method at the same time and may create two instances of MySingleton class. But using synchronized keyword may reduce the performance of the program.

Public class MySingleton(){
     private static MySingleton singletonInstance;

     private MySingleton(){
     
     }

     public static synchronized MySingleton getSigleton(){
         if(singletonInstance = null)
             singletonInstance = new MySingletn()
         return singletonInstance;
         }
}

The other option to create a Singleton class is to create the instance when class is loaded. Multi threading problems may not occur because before any of threads access the instance is already created when the class is loaded.

Public class MySingleton(){
     private static final MySingleton singletonInstance = new MySingleton()
     
     private MySingleton(){

     }

     public static MySingleton getMySingletn (){
         return singletonInstance;
     }
}

According to the performance of your program and needs, you can select which method would be better to create the Singleton class. If you are using several class loaders, it may create more than one instance. Singleton class cannot be subclassed because it has a private constructor.


Best way to create a  sigleton class is to use enum as described in Effective Java Reloaded by Joshua Bloch. Enum guarantees only one instance and thread safety. As the below code, we can declare enum Singleton easily. 

public enum MySigleton{

     INSTANCE;

     public void execute(){
         //Other functionalities
     }
}

We can get the singleton instance by using MySingleton.INSTANCE. 

2 comments: