好吧,实际上 Java 中的 Enum 只是用于声明整个类层次结构的语法糖。
写作:
public enum MyEnum {
FOO, BAR
}
大致相当于写
public abstract class MyEnum {
public static final MyEnum FOO = new MyEnum(){};
public static final MyEnum BAR = new MyEnum(){};
private MyEnum(){}
}
乍一看,这似乎有点矫枉过正,但您意识到您可以做所有类可以做的事情,例如:
public enum Operators {
ADD("+"){
public double apply(double lhs, double rhs){ return lhs + rhs; }
},
SUBTRACT("-"){
public double apply(double lhs, double rhs){ return lhs - rhs; }
},
MULTIPLY("*"){
public double apply(double lhs, double rhs){ return lhs * rhs; }
},
DIVIDE("/"){
public double apply(double lhs, double rhs){ return lhs / rhs; }
};
private final String symbol;
Operators(String symbol){
this.symbol = symbol;
}
public abstract double apply(double lhs, double rhs);
}
现在相当于(加上一些额外的便利方法):
public abstract class Operators {
public static final Operators ADD = new Operators("+"){
public double apply(double lhs, double rhs){ return lhs + rhs; }
};
public static final Operators SUBTRACT = new Operators("-"){
public double apply(double lhs, double rhs){ return lhs - rhs; }
};
public static final Operators MULTIPLY = new Operators("*"){
public double apply(double lhs, double rhs){ return lhs * rhs; }
},
public static final Operators DIVIDE = new Operators("/"){
public double apply(double lhs, double rhs){ return lhs / rhs; }
};
private final String symbol;
private Operators(String symbol){
this.symbol = symbol;
}
public abstract double apply(double lhs, double rhs);
}
我相信我们可以同意它比非常基本的 C 版本更强大。当然,使用枚举可以保证枚举的每个成员都是单例。