假设我正在构建一个不可变的 Yahtzee 记分卡类:
public final class Scorecard {
private Map<Category, Integer> scorecard = new HashMap<Category, Integer>();
public Scorecard() {
// Instantiates a new empty scorecard
}
private Scorecard(Map<Category, Integer> scorecard) {
this.scorecard = scorecard;
}
public Scorecard withScore(Category category, int[] roll) {
newScorecard = new HashMap<Category, Integer>(scorecard); // Pretend that this is a deep-copy
newScorecard.put(category, calculateScoreFromRoll(roll));
return new Scorecard(newScorecard);
}
public int getScore(Category category) {
return scorecard.get(category);
}
}
基本上我不想暴露班级的内部。如果我没有私有构造函数,那么我将需要使用带有Map
参数的公共构造函数,就像私有构造函数一样(而且我基本上也可能会丢失该withScore()
方法)以允许评分。但这是一种有效的工厂方法吗?