在 Java 中使用 Enum 作为单例的最佳方法是什么?
建立在 SO 问题 Best Singleton Implementing In 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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您要绑定到某个对象,该对象将使用给定的任何对象的属性 - 您可以非常轻松地传递 Elvis.INSTANCE,但不能传递 Elvis.class 并期望它找到该属性(除非故意编码以找到该属性)类的静态属性)。
基本上,只有当您想要实例时才使用单例模式。 如果静态方法适合您,那么只需使用它们,而不用担心枚举。
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.
一个很大的优势是当您的单例必须实现接口时。 按照你的例子:
使用:
它不能用静态来完成......
A great advantage is when your singleton must implements an interface. Following your example:
With:
It can't be done with statics...
(有状态)单例通常用于假装不使用静态变量。 如果你实际上不使用公共静态变量,那么你愚弄的人就会更少。
(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.
我会选择最简单、最清晰的选项。 这有点主观,但如果您不知道什么是最清楚的,就选择最短的选项。
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.