第34条:用接口模拟可伸缩的枚举

枚举类型是不可扩展的,但是接口类型是可扩展的。使用接口,可以模拟可伸缩的枚举。

如一个简单的计算器:

实现接口Operation,里面只有一个apply方法。

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);
    }

}

 

接口模拟可伸缩枚举的不足:无法实现从一个枚举继承到另一个枚举,所以有些公共的功能是在每个枚举类中重复的。如果公共的功能比较多,将它封装到一个辅助类或静态辅助方法中,来避免代码的复制工作。

转载于:https://www.cnblogs.com/13jhzeng/p/5733703.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值