(34):使用接口模拟可伸缩的枚举
来源:互联网 发布:戈博贝尔求生刀淘宝 编辑:程序博客网 时间:2024/05/22 06:30
在java中一个枚举是无法直接去扩展另一个枚举的,但通过接口我们可以变相的实现这一点。
public interface Operation { double apply(double x, double y);}
public enum BasicOperation implements Operation { PLUS("+") { public double apply(double x, double y) {return x + y;} }, MINUS("-") { public double apply(double x, double y) {return x - y;} }, TIMES("*") { public double apply(double x, double y) {return x - y;} }, DIVIDE("/") { public double apply(double x, double y) {return x - y;} }; private final String symbol; BasicOperation(String symbol) { this.symbol = symbol; } public String toString() { return symbol; } }
public enum ExtendedOperation implements Operation { EXP("^") { public double apply(double x, double y) {return Math.pow(x, y);} }, REMAINDER("%") { public double apply(double x, double y) {return x % y;} }; private final String symbol; private ExtendedOperation(String symbol) { this.symbol = symbol; } public String toString() { return symbol; }}客户端代码:
public class Main { private static <T extends Enum<T> & Operation> void test(Class<T> opSet, double x, double y) { for(Operation op : opSet.getEnumConstants()) System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y)); } public static void main(String[] args) { double x = 2.0; double y = 4.0; test(ExtendedOperation.class, x, y); }}总而言之,虽然无法编写可扩展的枚举类型 , 但是可以通过编写接口以及实现该接口的基础枚举类型对它进行模拟 . 这样允许客户端编写自己的枚举来实现接口 . 如果 API 是根据接口编写的,那么在可以使用基础枚举类型的任何地方 , 也都可以使用这些枚举 .
0 0
- (34):使用接口模拟可伸缩的枚举
- EffectiveJava(34) -- 使用接口模拟可伸缩的枚举
- 使用布局设计可伸缩的对话框
- 可伸缩的电子商务解决方案
- 可伸缩的TextView
- 可伸缩的TextView
- 模拟Material design实现可伸缩标题栏
- 使用setimmediate实现可伸缩执行的脚本
- 可伸缩的电子商务解决方案 2
- 可伸缩的搜索框
- Android ----可伸缩的控件
- 67. 可伸缩的 Comet
- 可伸缩展示的ListView
- 可拖动可伸缩的div
- 可伸缩的网络编程(Scalable Network Programming)
- 可伸缩系统的设计模式(译)
- [服务器开发]可伸缩系统的设计模式(译)
- 可伸缩矢量图形(SVG)样式的设置
- Memcached之——整合Spring完整示例
- 洛谷 P1227 [JSOI2008]完美的对称
- Python :连续正数序列
- [置顶]树剖例题
- Map.vue重构笔记
- (34):使用接口模拟可伸缩的枚举
- JavaScript中的方法
- C++ STL 栈stack 向量vector 队列queue的用法
- 三种算法求一个数字序列的最长递增子序列
- 集训-变形合唱队形(DP)
- 《拳皇咆哮》Cocos2dx 横版动作手游全套源码 + 资源 + 数据库
- tableWidget用法
- 用户界面设计
- POJ3026Borg Maze(BFS+prim最小生成树)