상태(State) 패턴
public class VendingMachine {
private Integer balance;
private Map<Integer, Product> products;
private State state;
public VendingMachine() {
balance = 0;
state = State.NOCOIN;
initProducts();
}
private void initProducts() {
products = new HashMap<>();
products.put(1, new Product("오이", 500));
products.put(2, new Product("참외", 1000));
}
public void insertCoin(int coin) {
switch (state) {
case NOCOIN:
increaseCoin(coin);
state = State.SELECTABLE;
break;
case SELECTABLE:
increaseCoin(coin);
}
}
public void select(int id) {
switch (state) {
case NOCOIN:
// Nothing
break;
case SELECTABLE:
provideProduct(id);
decreaseCoin(id);
if(hasNoCoin()) {
state = State.NOCOIN;
}
}
}
private void increaseCoin(int coin) {
this.balance += coin;
}
private void decreaseCoin(int id) {
this.balance -= products.get(id).price;
}
private boolean hasNoCoin() {
return balance == 0;
}
private String provideProduct(int id) {
return products.get(id).dispense();
}
private class Product {
private String name;
private int price;
private Product(String name, int price) {
this.name = name;
this.price = price;
}
String dispense() {
return name;
}
}
private enum State {
NOCOIN, SELECTABLE;
}
}상태 패턴 적용

상태 패턴의 장점
상태 변경은 누가 하는가?
Concrete State 객체에서 변경
Context 객체에서 변경
상태 객체에서 변경 VS Context 객체에서 변경
Enum을 이용한 상태(State) 패턴 및 Context 객체에서 상태 변경

Last updated