Thursday, 24 February 2011

An Easy Singleton

Writing a Singleton class can be a bit of a chore, you have to remember to do several things such as making your constructor private, implementing a proper getInstance() factory method and making it thread safe by making your instance variable volatile.

There is a quicker way, however, you can cheat and implement a singleton using an Enum:


public enum SingletonEnum {

 
/** The one and only instance we allow */
 
INSTANCE;

 
/**
   * This is our singleton method
   *
   *
@param param
   *            The param...
   */
 
public void singleMethod1(String param) {
   
System.out.println("This is param: " + param);
 
}

}

The example above is a simple enum with one instance value - our singleton and is called using this code:

    // enum singleton
   
SingletonEnum.INSTANCE.singleMethod1("Enum Singleton");