Implement Singleton pattern with a single-element enum
suggest changeAn enum type is initialized the first time it is actively used, and its constants are created then. A single constant can implement the Singleton pattern. Initialization is once per class loader, not once per JVM.
public enum Attendant {
INSTANCE;
private Attendant() {
// perform some initialization routine
}
public void sayHello() {
System.out.println("Hello!");
}
}
public class Main {
public static void main(String... args) {
Attendant.INSTANCE.sayHello();// instantiated at this point
}
}
Joshua Bloch's Effective Java recommends a single-element enum as the usual way to implement a singleton. This approach has the following advantages:
- thread safety
- guarantee of single instantiation
- out-of-the-box serialization
And as shown in the section implements interface this singleton might also implement one or more interfaces.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents