Monday, August 2, 2010

Most easiest and efficient way to create a Singleton in Java 5

The easiest and most efficient way to create a singleton in Java 5 is simply create an enum type with only one element.

For example:

public enum MySingleton {
INSTANCE;

public void doSomething()
{
System.out.println("Do something");
}
//--other methods will go here
}

Advantages:
No need to write the boiler-plate code of traditional approach such as making the constructor private, defining static final field, in case of serializable no need to define readResolve() method(will be taken care by enum), in mutli threaded application no need to handle synchronization explicitly, no threat of cloning etc.

No comments: