Effective Java - Item 3. Enforce the Singleton Property with a private Constructor or an Enum Type

Enforce singleton characteristics with a private constructor or an enum type.

In Java 1.5, Tiger, you can create a singleton by providing an enum type with a single element.

public enum MySingleton {
    INSTANCE;

    public void greet() { ... }
}

Compared with creating a singleton class by using a private static field, this has the following advantages.

  • It has serialization support.
    • You do not need to implementes Serializable.
  • It is resistant to serialization attacks.
    • You do not need to implement the readResolve method.
  • It is resistant to reflection attacks.