[Java] 싱글톤 객체 처리(getInstance())
yeoseon opened this issue · comments
Yun Yeoseon (Row) commented
관련 코드리뷰 내용 참고 (next-step/java-lotto#404 (comment))
LottoMachine을 싱글톤이라고 생각했지만 싱글톤 처리는 하지 않고 구현했었다.
public class LottoMachine {
private static ResultView resultView;
private static LottoMachine lottoMachine;
private LottoMachine() {
this.resultView = new ResultView();
}
public void operate(InputView inputView) {
Money money = new Money(inputView.getMoney());
Lottos lottos = lottoMachine.createLottos(money);
Lotto winningLotto = lottoMachine.createLotto(inputView.getWinningNumbers());
resultView.printResult(makeLottoResult(winningLotto, lottos), money);
}
...
public static LottoMachine getInstance() {
if(lottoMachine == null) {
lottoMachine = new LottoMachine();
}
return lottoMachine;
}
- 개선을 위해 무의미한 객체 생성을 막는 private 생성자를 추가해줬다.
- 또 멤버변수에 static으로 LottoMachine을 선언하여, 로직에서 이 것을 사용하도록 했다.
- Main에서 얘를 사용할 일이 있는데, 이는 getInstance()를 구현하여 해결했다.
public static void main(String[] args) {
LottoMachine.getInstance().operate(InputView.getInstance());
}