Java的枚举优于旧的“Typesafe Enum”模式? [英] Advantages of Java's enum over the old "Typesafe Enum" pattern?

查看:110
本文介绍了Java的枚举优于旧的“Typesafe Enum”模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JDK1.5之前的Java中,Typesafe Enum模式是实现只能获得有限数值的类型的通常方法:

In Java prior to JDK1.5, the "Typesafe Enum" pattern was the usual way to implement a type that can only take a finite number of values:

public class Suit {
    private final String name;

    public static final Suit CLUBS =new Suit("clubs");
    public static final Suit DIAMONDS =new Suit("diamonds");
    public static final Suit HEARTS =new Suit("hearts");
    public static final Suit SPADES =new Suit("spades");    

    private Suit(String name){
        this.name =name;
    }
    public String toString(){
        return name;
    }
}

(参见例如Bloch的 Java

(see e.g. Item 21 from Bloch's Effective Java).

现在在JDK1.5 +中,官方的方式显然是使用枚举

Now in JDK1.5+, the "official" way is obviously to use enum:

public enum Suit {
  CLUBS("clubs"), DIAMONDS("diamonds"), HEARTS("hearts"), SPADES("spades");

  private final String name;

  private Suit(String name) {
    this.name = name;
  }
}

显然,语法有点更好,更简洁(不需要明确定义值的字段,适合 toString()提供),但到目前为止枚举看起来很非常类似于Typesafe Enum模式。

Obviously, the syntax is a bit nicer and more concise (no need to explicitly define fields for the values, suitable toString() provided), but so far enum looks very much like the Typesafe Enum pattern.

其他差异我知道:


  • 枚举自动提供 values()方法

  • 枚举可用于 switch()(编译器甚至检查你不会忘记一个值)

  • enums automatically provide a values() method
  • enums can be used in switch() (and the compiler even checks that you don't forget a value)

但这一切看起来都不像语法糖,甚至有一些限制(例如枚举始终从 java.lang.Enum 继承,并且不能

But this all looks like little more than syntactic sugar, with even a few limitations thrown in (e.g. enum always inherits from java.lang.Enum, and cannot be subclassed).

有没有其他更为根本的好处,枚举提供了无法实现的Typesafe枚举模式?

Are there other, more fundamental benefits that enum provides that could not be realized with the Typesafe Enum pattern?

推荐答案


  • 不能被子类化不是限制。这是一个很大的优点:它确保总是只有在枚举中定义的值集合,而不再有!

  • 枚举正确处理序列化。您可以使用类型安全的枚举来执行此操作,但常常被遗忘(或根本不知道)。这确保 e1.equals(e2) 始终意味着 e1 == e2 任何两个枚举 e1 e2 (反之亦然,这可能更重要)

  • 有特定的轻量级数据结构处理枚举: EnumSet 枚举地图(从此答案窃取)

    • "cannot be subclassed" isn't a restriction. It's one of the big advantages: It ensures there there is always only ever exactly the set of values defined in the enum and no more!
    • enum correctly handles serialization. You can do that with type-safe enums as well, but it's often forgotten (or simply not known). This ensures that e1.equals(e2) always implies e1 == e2 for any two enum values e1 and e2 (and vice versa, which is probably more important).
    • There are specific lightweight data structures that handle enums: EnumSet and EnumMap (stolen from this answer)
    • 这篇关于Java的枚举优于旧的“Typesafe Enum”模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆