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

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

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


当前回答

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

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

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

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

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

其他回答

在我看来,你到目前为止的所有答案都是正确的,但根据我的经验,我想用几句话来表达:

如果希望编译器检查标识符值的有效性,请使用枚举。

否则,您可以像往常一样使用字符串(可能您为应用程序定义了一些“约定”),并且您将非常灵活……但是你不能在你的字符串上获得100%的安全,你只能在运行时意识到它们。

基于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

枚举以自记录的方式枚举一组固定的值。 它们使您的代码更显式,也更不容易出错。

为什么不使用String,或int,而不是Enum常量?

编译器不允许错别字,也不允许出值的修正 设置,因为枚举本身就是类型。后果: 你不需要写一个先决条件(或手册)来确保你的论点在有效范围内。 类型不变式是免费的。 枚举可以有行为,就像任何其他类一样。 无论如何,您可能需要类似数量的内存来使用string(这取决于Enum的复杂性)。

此外,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)游戏作为枚举。

除了前面提到的用例,我经常发现枚举对于实现策略模式很有用,遵循一些基本的面向对象原则:

将代码放在数据所在的位置(即在枚举本身中——或者通常在枚举常量中,这可能会覆盖方法)。 实现一个(或更多)接口,以便不将客户端代码绑定到枚举(它应该只提供一组默认实现)。

最简单的例子是一组Comparator实现:

enum StringComparator implements Comparator<String> {
    NATURAL {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareTo(s2);
        }
    },
    REVERSE {
        @Override
        public int compare(String s1, String s2) {
            return NATURAL.compare(s2, s1);
        }
    },
    LENGTH {
        @Override
        public int compare(String s1, String s2) {
            return new Integer(s1.length()).compareTo(s2.length());
        }
    };
}

这种“模式”可以在更复杂的场景中使用,广泛使用枚举附带的所有优点:遍历实例,依赖于它们的隐式顺序,根据实例名称检索实例,为特定上下文提供正确实例的静态方法等等。你仍然把这些都隐藏在接口后面,这样你的代码就可以在不需要修改的情况下使用自定义实现,以防你想要一些“默认选项”中不可用的东西。

我曾看到这种方法成功地应用于时间粒度(每天、每周等)概念的建模,其中所有逻辑都封装在枚举中(为给定的时间范围选择正确的粒度,将特定行为绑定到每个粒度作为常量方法等)。而且,服务层所看到的粒度只是一个接口。