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

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

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


当前回答

枚举?为什么要使用它?我认为当你使用它的时候会更容易理解。我也有同样的经历。

假设您有一个创建、删除、编辑和读取数据库操作。

现在如果你创建一个枚举作为一个操作:

public enum operation {
    create("1")
    delete("2")
    edit("3")
    read("4")

    // You may have is methods here
    public boolean isCreate() {
        return this.equals(create);
    }
    // More methods like the above can be written

}

现在,你可以这样声明:

private operation currentOperation;

// And assign the value for it 
currentOperation = operation.create

所以你可以在很多方面使用它。对于特定的事情使用enum总是好的,因为上面例子中的数据库操作可以通过检查currentOperation来控制。也许有人会说,这也可以用变量和整数值来实现。但我相信Enum更安全,更适合程序员。

另一件事:我认为每个程序员都喜欢布尔,不是吗?因为它只能存储两个值,两个特定的值。所以Enum可以被认为具有相同类型的功能,用户可以定义它将存储多少和什么类型的值,只是方式略有不同。:)

其他回答

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

枚举是什么

enum是为枚举定义的关键字,是一种新的数据类型。应该广泛使用类型安全枚举。特别是,它们是较老api中用来表示相关项集的简单String或int常量的健壮替代。

为什么使用enum

enum是java.lang.Enum的隐式final子类 如果枚举是类的成员,则它是隐式静态的 New永远不能用于枚举,即使是在枚举类型本身中 name和valueOf简单地使用枚举常量的文本,而toString可以被覆盖以提供任何内容,如果需要的话 对于枚举常量,equals和==等于同一个东西,并且可以互换使用 枚举常量是隐式的公共静态final

Note

枚举不能扩展任何类。 enum不能是超类。 枚举常量的出现顺序被称为它们的“自然顺序”,并定义了其他项使用的顺序:compareTo,值的迭代顺序,EnumSet, EnumSet.range。 枚举可以有构造函数、静态和实例块、变量和方法,但不能有抽象方法。

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

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

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

此外,Enum的每个实例都是一个类,您可以为其定义单独的行为。

另外,它们在创建实例时(当枚举被加载时)确保线程安全,这在简化单例模式中有很好的应用。

这篇博客说明了它的一些应用,比如解析器的状态机。

知道枚举就像其他具有常量字段和私有构造函数的类一样是有用的。

例如,

public enum Weekday
{
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
} 

编译器按如下方式编译它;

class Weekday extends Enum
{
  public static final Weekday MONDAY  = new Weekday( "MONDAY",   0 );
  public static final Weekday TUESDAY = new Weekday( "TUESDAY ", 1 );
  public static final Weekday WEDNESDAY= new Weekday( "WEDNESDAY", 2 );
  public static final Weekday THURSDAY= new Weekday( "THURSDAY", 3 );
  public static final Weekday FRIDAY= new Weekday( "FRIDAY", 4 );
  public static final Weekday SATURDAY= new Weekday( "SATURDAY", 5 );
  public static final Weekday SUNDAY= new Weekday( "SUNDAY", 6 );

  private Weekday( String s, int i )
  {
    super( s, i );
  }

  // other methods...
}

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