89

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()

4 Answers 4

96

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.

Sign up to request clarification or add additional context in comments.

16 Comments

Why not bother with the enum? Is there a better way to do singeltons in java5+?
@jontro (re)read the answer; he says to use enums when you must have a singleton but to avoid singleton if you can make do with static methods
@MiserableVariable I commented on this over a year ago. Cant really remember what the context I was referring to.
doesn't answer the asked question
@Thufir: It answers the "what's the difference" part - which appears to be what the OP was most interested in, given that the answer was accepted.
|
69

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...

1 Comment

It can be done with statics... public static final HasAge INSTANCE = new HasAge() { private int age; @Override public int getAge() { return age; } }; ... so I'm still wondering what is good or better about the enum method. I suppose if you needed to implement two interfaces?
9

(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.

Comments

8

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.