Java的枚举优于旧的“Typesafe Enum”模式? [英] Advantages of Java's enum over the old "Typesafe Enum" pattern?
问题描述
在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 thate1.equals(e2)
always impliese1 == e2
for any twoenum
valuese1
ande2
(and vice versa, which is probably more important).- There are specific lightweight data structures that handle enums:
EnumSet
andEnumMap
(stolen from this answer)
这篇关于Java的枚举优于旧的“Typesafe Enum”模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!