Singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance.
Possible Java Implementations
Traditional simple way
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
Notes: If laziness is not needed or the instance needs to be created early in the application’s execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this solution can be used.
The solution of Bill Pugh
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Notes: The technique is known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. The implementation relies on the well-specified initialization phase of execution within the JVM. The inner class (SingletonHolder) is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called.
Java 5 Way! a.k.a Joshua Bloch way.
public enum Singleton {
INSTANCE;
public void myUsefulMethod1(){...}
...
}
Usage: Singleton.INSTANCE.myUsefulMethod1();
Credits: Effective Java 2nd Edn, Wiki