What is the best approach for using an Enum as a singleton in Java?

JavaSingleton

Java Problem Overview


Building on what has been written in SO question Best Singleton Implementation In Java - namely about using an enum to create a singleton - what are the differences/pros/cons between (constructor omitted)

public enum Elvis {
    INSTANCE;
    private int age;

    public int getAge() {
        return age;
    }
}

and then calling Elvis.INSTANCE.getAge()

and

public enum Elvis {
    INSTANCE;
    private int age;

    public static int getAge() {
        return INSTANCE.age;
    }
}

and then calling Elvis.getAge()

Java Solutions


Solution 1 - Java

Suppose you're binding to something which will use the properties of any object it's given - you can pass Elvis.INSTANCE very easily, but you can't pass Elvis.class and expect it to find the property (unless it's deliberately coded to find static properties of classes).

Basically you only use the singleton pattern when you want an instance. If static methods work okay for you, then just use those and don't bother with the enum.

Solution 2 - Java

A great advantage is when your singleton must implements an interface. Following your example:

public enum Elvis implements HasAge {
    INSTANCE;
    private int age;

    @Override
    public int getAge() {
        return age;
    }
}

With:

public interface HasAge {
    public int getAge();
}

It can't be done with statics...

Solution 3 - Java

(Stateful) Singletons are generally used to pretend not to be using static variables. If you don't actually use the publicly static variable then you will fool less people.

Solution 4 - Java

I would choose the option which is the simplest and clearest. This is somewhat subjective, but if you don't know what is clearest, just go for the shortest option.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiles DView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaNicolasView Answer on Stackoverflow
Solution 3 - JavaTom Hawtin - tacklineView Answer on Stackoverflow
Solution 4 - JavaPeter LawreyView Answer on Stackoverflow