Thursday, May 12, 2016



Best way to create a Singleton Pattern.


The Singleton Design Pattern is one of the Creational (creation of instance in best possible way) patterns.

The usage of enum, a new feature from Java5, allows safe way to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in memory (JVM).

This singleton instance is accessible from anywhere since Java Enum values are globally accessible.

The drawback is that the enum type is somewhat inflexible as it does not allow lazy
initialization.

package org.comp.core;
public enum MyEnumSingleton {
INSTANCE;

       private MyEnumSingleton(){}


  public static void method1(){

//Do something 
}

  public static List buildStateCodeList(){
              final List<String>  stateCodeList = new ArrayList<String>();
             stateCodeList.add("AR");
             stateCodeList.add("AZ");
             ....
             ....
             return stateCodeList ;
}
}

From Caller:
List<String> stateCode_USA_List = MyEnumSingleton.INSTANCE.buildStateCodeList();


The following is more appropriate in  Distributed environment.   

package org.comp.core;
import java.io.*;
public class MySerializedSingleton implements Serializable{
private static final long serialVersionUID = -12345678923456789123L;
// Private/default constructor
private MySerializedSingleton(){}
//Inner static class to create instance (A safer way)
private static class MySingletonHelper{
private static final MySerializedSingleton instance = new MySerializedSingleton();
}

//Return singleton instance
public static MySerializedSingleton getInstance(){
return MySingletonHelper.instance;
}

/**
* Implement the readResolve() method to avoid creating a new instance in 'Deserialization'            scenario.  
*/
protected Object readResolve() {
return getInstance();
}

}

No comments:

Post a Comment