【发布时间】:2014-03-19 08:41:32
【问题描述】:
我有以下代码,我相信我明白了为什么我得到了错误:
错误是,例如:
-
初始化器中的自引用在
ROCKRPSGesture.ROCK的构造函数中。 -
非法前向引用在
ROCKRPSGesture.PAPER的构造函数中。
public interface Gesture {
public List<? extends Gesture> winsFrom();
public List<? extends Gesture> tiesTo();
public List<? extends Gesture> losesTo();
}
public enum RPSGesture implements Gesture, Action {
ROCK(
Arrays.asList(RPSGesture.SCISSORS),
Arrays.asList(RPSGesture.ROCK),
Arrays.asList(RPSGesture.PAPER)
),
PAPER(
Arrays.asList(RPSGesture.ROCK),
Arrays.asList(RPSGesture.PAPER),
Arrays.asList(RPSGesture.SCISSORS)
),
SCISSORS(
Arrays.asList(RPSGesture.PAPER),
Arrays.asList(RPSGesture.SCISSORS),
Arrays.asList(RPSGesture.ROCK)
);
private final List<RPSGesture> winsFrom;
private final List<RPSGesture> tiesTo;
private final List<RPSGesture> losesTo;
private RPSGesture(final List<RPSGesture> winsFrom, final List<RPSGesture> tiesTo, final List<RPSGesture> losesTo) {
this.winsFrom = winsFrom;
this.tiesTo = tiesTo;
this.losesTo = losesTo;
}
@Override
public List<RPSGesture> winsFrom() {
return winsFrom;
}
@Override
public List<RPSGesture> tiesTo() {
return tiesTo;
}
@Override
public List<RPSGesture> losesTo() {
return losesTo;
}
}
我见过Peter Lawrey's Answer,但是static 初始化器真的是最好的方法吗?还有其他合理的选择吗?
这个枚举的设计看起来是否正确,或者你自己会做不同的事情吗?希望类中的代码更少。
【问题讨论】:
-
好吧,你总是
tiesTo()自己,不是吗?只需让tiesTo()返回Collections.<Gesture>singletonList(this)... -
@fge 我不太确定。在常规的 Rock-Paper-Scissors 中是的,但是在自定义变体中,您可能能够绑定多个手势。
-
要么是
static初始化器(在enum的情况下,这与构造函数相同)或者只是实现方法 inenum实例。