枚举类型( BasicOperation )不可扩展,但接口类型( Operation )是可以扩展的,并且它是用于表
示 API 中的操作的接口类型。
1 // Emulated extensible enum using an interface 2 public interface Operation { 3 double apply(double x, double y); 4 } 5 6 // Emulated extension enum 7 public enum ExtendedOperation implements Operation { 8 EXP("^") { 9 public double apply(double x, double y) { 10 return Math.pow(x, y); 11 } 12 }, 13 REMAINDER("%") { 14 public double apply(double x, double y) { 15 return x % y; 16 } 17 }; 18 19 private final String symbol; 20 ExtendedOperation(String symbol) { 21 this.symbol = symbol; 22 } 23 @Override 24 public String toString() { 25 return symbol; 26 } 27 }
public static void main(String[] args) { double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); test(ExtendedOperation.class, x, y); }
private static <T extends Enum<T> & Operation> void test(Class<T> opEnumType, double x, double y) { for (Operation op : opEnumType.getEnumConstants()){
System.out.printf("%f %s %f = %f%n",x, op, y, op.apply(x, y));
} }
or
public static void main(String[] args) { double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); test(Arrays.asList(ExtendedOperation.values()), x, y); } private static void test(Collection<? extends Operation> opSet,double x, double y) { for (Operation op : opSet) System.out.printf("%f %s %f = %f%n",x, op, y, op.apply(x, y)); }
下面的方法灵活一点:它允许调用者将多个实现类型的操作组合在一起,另一方面,也放弃了在指定操作上使用 EnumSet 和 EnumMap 的能力。
使用接口来模拟可扩展枚举的一个小缺点是,实现不能从一个枚举类型继承到另一个枚举类型。
总之,虽然不能编写可扩展的枚举类型,但是你可以编写一个接口来配合实现接口的基本的枚举类型,来对它进
行模拟。 这允许客户端编写自己的枚举(或其它类型)来实现接口。如果 API 是根据接口编写的,那么在任何使
用基本枚举类型实例的地方,都可以使用这些枚举类型实例。
effective-java学习笔记---使用接口模拟可扩展的枚举38
原文:https://www.cnblogs.com/zsmcwp/p/11606891.html