Singleton Classes

The most common way is using private constructor with static final member or factory method.

public class Elvis {
    public static final INSTANCE;
    private Elvis() { ... }
}

Or you may use an enum type with one element.

public enum Elvis {
    INSTANCE;
}

Note that singleton classes make their clients harder to test (you cannot easily mock them out).

Creative Commons License
This blog by Che-Liang Chiou is licensed under a Creative Commons Attribution 4.0 International License.