我有以下代码,我相信我看到为什么我得到错误:
错误如下:
-
ROCK
在RPSGesture.ROCK
的构造函数中初始化式的自引用。 -
ROCK
在RPSGesture.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的回答,然而static
初始化器真的是最好的方法吗?还有其他合理的选择吗?
这个枚举的设计看起来正确吗,或者你自己会做不同的设计吗?希望类中的代码更少。
我自己找到了一个合适的方法,使用Java 8:
public interface Gesture {
public List<? extends Gesture> winsFrom();
public List<? extends Gesture> tiesTo();
public List<? extends Gesture> losesTo();
}
public enum RPSGesture implements Gesture, Action, RuleGestureFPSFactory {
ROCK,
PAPER,
SCISSORS;
@Override
public List<RPSGesture> winsFrom() {
return winMapping().get(this);
}
@Override
public List<RPSGesture> tiesTo() {
return tieMapping().get(this);
}
@Override
public List<RPSGesture> losesTo() {
return loseMapping().get(this);
}
}
public interface RuleGestureFactory<T extends Gesture> {
public Map<T, List<T>> winMapping();
public Map<T, List<T>> tieMapping();
public Map<T, List<T>> loseMapping();
}
public interface RuleGestureFPSFactory extends RuleGestureFactory<RPSGesture> {
@Override
default public Map<RPSGesture, List<RPSGesture>> winMapping() {
Map<RPSGesture, List<RPSGesture>> mapping = new HashMap<>();
mapping.put(ROCK, Arrays.asList(SCISSORS));
mapping.put(PAPER, Arrays.asList(ROCK));
mapping.put(SCISSORS, Arrays.asList(PAPER));
return mapping;
}
@Override
default public Map<RPSGesture, List<RPSGesture>> tieMapping() {
Map<RPSGesture, List<RPSGesture>> mapping = new HashMap<>();
mapping.put(ROCK, Arrays.asList(ROCK));
mapping.put(PAPER, Arrays.asList(PAPER));
mapping.put(SCISSORS, Arrays.asList(SCISSORS));
return mapping;
}
@Override
default public Map<RPSGesture, List<RPSGesture>> loseMapping() {
Map<RPSGesture, List<RPSGesture>> mapping = new HashMap<>();
mapping.put(ROCK, Arrays.asList(PAPER));
mapping.put(PAPER, Arrays.asList(SCISSORS));
mapping.put(SCISSORS, Arrays.asList(ROCK));
return mapping;
}
}
这样你甚至可以很容易地有不同的规则实现,但是它不支持在运行时切换。