Home > DeveloperSection > Forums > Singleton pattern in Java?
Mikki Halpin
Mikki Halpin

Total Post:23

Posted on    July-17-2015 10:59 PM

 Java Java 

 1 Reply(s)
 705  View(s)
Rate this:
What is an efficient way to implement a singleton pattern in Java?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    July-18-2015 8:06 AM

Use an enum:

public enum Foo {
public enum Elvis {
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {

"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

Don't want to miss updates? Please click the below button!

Follow MindStick