第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