Implement Singleton pattern with a single-element enum

suggest change

An 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:

And as shown in the section implements interface this singleton might also implement one or more interfaces.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents