如果你的语言里面没有枚举类型,那么可以使用全局变量或者类来模拟它,例如可以再java中使用如下声明
calss Country{
private Country(){}
public static final Country China = new Country();
public static final Country England= new Country();
public static final Country France= new Country();
public static final Country Germany= new Country();
public static final Country Japan= new Country();
}
class Output{
private Output(){}
public static final Output Screen = new Output();
public static final Output Printer= new Output();
public static final Output File= new Output();
}
这些枚举类型会增强你的程序的可读性,因为你可以使用Country.England和Output.Screen等公用类成员来代替具名常量。这种特殊的创建枚举类型的方法还是类型安全的;因为每种类型都声明为类,因此编译器会检查非法的赋值,比如Output output = Country.England (Bloch 2001).
在不支持类的语言中,你也可以通过对全局变量的规范应用来模拟枚举类型中的每一个元素,从而获得同样的基本效果
本文转自代码大全第二版中的 第12章基本数据类型 部分 ,觉得这种方法很实用,特此记录以备后用