今天我浏览了这个网站上的一些问题,我发现一个枚举被用于单例模式,据称线程安全的好处,这种解决方案。

我从来没用过枚举,而且我已经用Java编程好几年了。显然,他们改变了很多。现在他们甚至在自己内部完全支持OOP。

为什么我应该在日常编程中使用enum ?


当前回答

Something none of the other answers have covered that make enums particularly powerful are the ability to have template methods. Methods can be part of the base enum and overridden by each type. And, with the behavior attached to the enum, it often eliminates the need for if-else constructs or switch statements as this blog post demonstrates - where enum.method() does what originally would be executed inside the conditional. The same example also shows the use of static imports with enums as well producing much cleaner DSL like code.

其他一些有趣的特性包括枚举提供equals()、toString()和hashCode()的实现,并实现Serializable和Comparable。

我强烈推荐Bruce Eckel的《Thinking in Java》第4版,它用了整整一章来讨论这个主题。特别具有启发性的例子是将石头剪子布(即RoShamBo)游戏作为枚举。

其他回答

使用枚举类型安全,这是一个语言特性,所以你通常会得到:

编译器支持(立即查看类型问题) ide中的工具支持(在切换情况下自动补全,缺失情况,强制默认,…) 在某些情况下,枚举的性能也很好(EnumSet,类型安全的替代传统的基于int的“位标志”)。

枚举可以有方法、构造函数,甚至可以在枚举中使用枚举,并将枚举与接口结合使用。

可以将枚举看作是替换一组定义良好的int常量的类型(Java从C/ c++“继承”了int常量),在某些情况下还可以替换位标志。

《Effective Java 2nd Edition》一书中有一整章是关于它们的,并且有更多的细节。也可以参考Stack Overflow的文章。

从Java文档-

您应该在任何时候使用枚举类型 需要表示一个固定的集合 常量。包括自然enum 比如我们太阳系中的行星 你知道的系统和数据集 编译时所有可能的值 时间——例如,a上的选项 菜单、命令行标志等等。

一个常见的例子是用枚举类型替换一个类,用一组私有静态final int常量(常量数量合理)。基本上,如果你认为你在编译时知道“something”的所有可能值,你可以将其表示为枚举类型。比起带有常量的类,枚举提供了可读性和灵活性。

枚举类型几乎没有其他优点。它们总是特定枚举类的一个实例(因此出现了使用枚举作为单例的概念)。另一个优点是可以在switch-case语句中使用枚举作为类型。你也可以在枚举上使用toString()将它们打印为可读的字符串。

基于enum的单例

一个老问题的现代视角

这种方法通过利用Java的保证来实现单例,即任何enum值在Java程序中只实例化一次,并且enum为线程安全提供了隐式支持。由于Java枚举值是全局可访问的,因此它们可以作为单例使用。

public enum Singleton {
    SINGLETON; 
    public void method() { }
}

这是如何工作的呢?好吧,代码的第二行可以被认为是这样的:

public final static Singleton SINGLETON = new Singleton(); 

我们得到了早期初始化的单例。

记住,因为这是一个枚举,你总是可以通过Singleton访问实例。单例也是:

Singleton s = Singleton.SINGLETON;

优势

To prevent creating other instances of singleton during deserialization use enum based singleton because serialization of enum is taken care by JVM. Enum serialization and deserialization work differently than for normal java objects. The only thing that gets serialized is the name of the enum value. During the deserialization process, the enum valueOf method is used with the deserialized name to get the desired instance. Enum based singleton allows to protect itself from reflection attacks. The enum type actually extends the java Enum class. The reason that reflection cannot be used to instantiate objects of enum type is that the java specification disallows and that rule is coded in the implementation of the newInstance method of the Constructor class, which is usually used for creating objects via reflection:

if ((clazz.getModifiers() & Modifier.ENUM) != 0)
    throw new IllegalArgumentException("Cannot reflectively create enum objects");

Enum不应该被克隆,因为每个值必须只有一个实例。 所有单例实现中最简洁的代码。

缺点

The enum based singleton does not allow lazy initialization. If you changed your design and wanted to convert your singleton to multiton, enum would not allow this. The multiton pattern is used for the controlled creation of multiple instances, which it manages through the use of a map. Rather than having a single instance per application (e.g. the java.lang.Runtime) the multiton pattern instead ensures a single instance per key. Enum appears only in Java 5 so you can not use it in the prior version.

单例模式有几种实现方式,每一种都有优缺点。

急装单件 双重检查锁定单例 初始化-按需holder习语 基于enum的单例

详细的描述每个都太啰嗦了,所以我只是放了一个链接到一篇好文章-所有你想知道的关于Singleton

ENum代表“枚举类型”。它是一种具有一组固定常数的数据类型,由您自己定义。

Java允许将变量限制为只有几个预定义值之一——换句话说,枚举列表中的一个值。 使用枚举可以帮助减少代码中的bug。 下面是一个类外部枚举的例子:

enums coffeesize{BIG , HUGE , OVERWHELMING }; 
//This semicolon is optional.

这限制了咖啡的大小:大的,巨大的,或压倒性的变量。