From Effective Java 2/e by Joshua Bloch
Hard to test client if the class itself is a singleton
Two ways to make singleton before Java 1.5
// Singleton with public final field public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {...} } // Singleton with static factory public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {...} public static Elvis getInstance() { return INSTANCE; } }
// readResolve method to preserve singleton property private Object readResolve() { // Return the one true Elvis and let the garbage collector // take care of the Elvis impersonator. return INSTANCE; } // Enum singleton - the preferred approach public enum Elvis { INSTANCE; public void leaveTheBuilding() { ... } }