【发布时间】:2015-02-02 12:14:32
【问题描述】:
正如here 指出的那样,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... -
你可以有很多方法,在一个枚举中互相调用。它们的签名可能与任何标准功能接口都不匹配。顺便说一句,在您的第一个 sn-p 中,您的操作()方法应该被声明为抽象的,而不是提供一个实现。
-
另一种方式(在您的具体示例中)是
enum Operator implements BinaryOperator<Integer>,然后直接实现apply。 -
我喜欢你的 lambdas 解决方案,它看起来比方法覆盖干净得多。
-
顺便说一句,你可以使用接口来实现这个逻辑。