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.
- You do not need to
- It is resistant to serialization attacks.
- You do not need to implement the
readResolvemethod.
- You do not need to implement the
- It is resistant to reflection attacks.