正如在这里指出的那样,lambda表达式为指定每个枚举值的行为提供了一种非常优雅的方式。
在Java 8之前,我通常会以以下方式实现:
enum Operator {
TIMES {
public int operate(int n1, int n2) {
return n1 * n2;
}
},
PLUS {
public int operate(int n1, int n2) {
return n1 + n2;
}
};
public int operate(int n1, int n2) {
throw new AssertionError();
}
}
现在我倾向于使用:
enum Operator {
TIMES((n1, n2) -> n1 * n2),
PLUS((n1, n2) -> n1 + n2);
private final BinaryOperator<Integer> operation;
private Operator(BinaryOperator<Integer> operation) {
this.operation = operation;
}
public int operate(int n1, int n2) {
return operation.apply(n1, n2);
}
}
这看起来更加优美。
我现在想不到为一个特定的枚举值而重写方法的原因。所以我的问题是,在 enum
中使用方法重写有没有好的理由,或者应该总是优先考虑使用函数接口?
public int operate
... - tobias_kenum Operator implements BinaryOperator<Integer>
,然后直接实现apply
。 - tobias_k