不変の 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()
しかし、これはファクトリメソッドを実行する有効な方法ですか?