在 Java 中使用 Enum 作为单例的最佳方法是什么?

基于在 SO 问题 Java 中最佳单例实现中所写的内容——也就是关于使用枚举来创建单例模式的内容——构造函数省略了构造函数之间的差异/利弊

public enum Elvis {
INSTANCE;
private int age;


public int getAge() {
return age;
}
}

然后打电话给 Elvis.INSTANCE.getAge()

还有

public enum Elvis {
INSTANCE;
private int age;


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

然后打电话给 Elvis.getAge()

77605 次浏览

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.

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

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

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.