售出状态(SoldState)
售出状态是售货机发放商品的状态。如果用户插入了硬币,售货机将扣除商品价格,并切换到待机状态;如果用户按下按钮,售货机将提示用户需要先插入硬币;如果用户尝试发放商品,售货机将发放商品。
代码语言:javascript复制public class SoldState implements State {
private VendingMachine vendingMachine;
public SoldState(VendingMachine vendingMachine) {
this.vendingMachine = vendingMachine;
}
@Override
public void insertCoin() {
System.out.println("Please wait, we're already giving you a product.");
}
@Override
public void pressButton() {
System.out.println("You have not inserted a coin yet.");
}
@Override
public void dispense() {
if (vendingMachine.getCount() > 0) {
vendingMachine.setCount(vendingMachine.getCount() - 1);
System.out.println("Product dispensed.");
if (vendingMachine.getCount() == 0) {
vendingMachine.setCurrentState(new NoStockState(vendingMachine));
} else {
vendingMachine.setCurrentState(new IdleState(vendingMachine));
}
} else {
vendingMachine.setCurrentState(new NoStockState(vendingMachine));
}
}
}
在SoldState类中,我们实现了State接口中的三个行为方法:插入硬币方法insertCoin()、按下按钮方法pressButton()和发放商品方法dispense()。如果用户插入了硬币,售货机将扣除商品价格,并切换到待机状态(IdleState);如果用户按下按钮,售货机将提示用户需要先插入硬币;如果用户尝试发放商品,售货机将发放商品,并切换到待机状态(IdleState)或无库存状态(NoStockState)。