例如:

/**
 * 加减乘除枚举
 * Created by yulinfeng on 8/20/17.
 */
public enum Operation {
    PLUS {
        double apply(double x, double y) {
            return x + y;
        }
    },
    MIUS {
        double apply(double x, double y) {
            return x - y;
        }
    },
    TIMES {
        double apply(double x, double y) {
            return x * y;
        }
    },
    DEVIDE {
        double apply(double x, double y) {
            return x / y;
        }
    };

    abstract double apply(double x, double y);
}
View Code

同时提到当需要新增一个操作符时直接在源代码中新增即可,且不会忘记重写apply方法,但从软件开发的可扩展性来说这并不是一个好的方法,软件可扩展性并不是在原有代码上做修改,如果这段代码是在jar中的呢?这个时候就需要接口出场了,我们修改上述例子:

/**
 * 操作符接口
 * Created by yulinfeng on 8/20/17.
 */
public interface Operation {
    double apply(double x, double y);
}
View Code
/**
 * 基本操作符,实现自Operation接口
 * Created by yulinfeng on 8/20/17.
 */
public enum BasicOperation implements Operation{
    PLUS("+") {
        public double apply(double x, double y) {
            return x + y;
        }
    },
    MIUS("-") {
        public double apply(double x, double y) {
            return x - y;
        }
    },
    TIMES ("*") {
        public double apply(double x, double y) {
            return x * y;
        }
    },
    DEVIDE ("/") {
        public double apply(double x, double y) {
            return x / y;
        }
    };
    private final String symbol;

    BasicOperation(String symbol) {
        this.symbol = symbol;
    }
}
View Code

当我们需要扩展操作符枚举的时候只需要重新实现Operation接口即可:

/**
 * 扩展操作符
 * Created by yulinfeng on 8/20/17.
 */
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;

    ExtendedOperation(String symbol) {
        this.symbol = symbol;
    }
}
View Code