在要求使用一个枚举类型的环境下,咱们首先应该考虑类型安全枚举模式。 java
// 这是类型安全枚举模式的一个简单实现。 public class Suit { private final String name; private Suit(String name) { this.name = name; } public String toString() { return this.name; } public static final Suit CLUBS = new Suit("clubs"); public static final Suit DIAMONDS = new Suit("diamonds"); public static final Suit HEARTS = new Suit("hears"); public static final Suit SPADES = new Suit("spades"); }
在C语言标准库中的qsort,该函数要求一个指向comparator函数的指针做为参数,它用这个函数来比较排序的元素。这种用途其实是实现了Strategy模式。为了在JAVA中实现这种模式,声明一个接口来表示该策略,而且为每一个具体策略声明一个实现了该接口的类。 安全
比较器的实现请参考 http://my.oschina.net/u/1453800/blog/232712 的匿名类这一节。 函数