比方說,我要建一個不變的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()
方法)以允許評分。但這是做工廠方法的有效方式嗎?
這聽起來像你在說什麼更多的是一種生成器比一個工廠,但沒錯,這是一個很好的方法。 – chrylis
@chrylis你會說工廠方法不應該建立在現有的實例上嗎? –
我無法理解這個問題。 – chrylis