publicGumballMachine(int count){ this.count = count; if (count > 0) { state = NO_QUARTER; } }
publicvoidinsertQuarter(){ if (state == HAS_QUARTER) { System.out.println("You can't insert another quarter"); } elseif (state == NO_QUARTER) { state = HAS_QUARTER; System.out.println("You inserted a quarter"); } elseif (state == SOLD_OUT) { System.out.println("You can't insert a quarter, the machine is sold out"); } elseif (state == SOLD) { System.out.println("Please wait, we're already giving you a gumball"); } }
publicvoidejectQuarter(){ if (state == HAS_QUARTER) { System.out.println("Quarter returned"); state = NO_QUARTER; } elseif (state == NO_QUARTER) { System.out.println("You haven't inserted a quarter"); } elseif (state == SOLD) { System.out.println("Sorry, you already turned the crank"); } elseif (state == SOLD_OUT) { System.out.println("You can't eject, you haven't inserted a quarter yet"); } }
publicvoidturnCrank(){ if (state == SOLD) { System.out.println("Turning twice doesn't get you another gumball!"); } elseif (state == NO_QUARTER) { System.out.println("You turned but there's no quarter"); } elseif (state == SOLD_OUT) { System.out.println("You turned, but there are no gumballs"); } elseif (state == HAS_QUARTER) { System.out.println("You turned..."); state = SOLD; dispense(); } }
privatevoiddispense(){ if (state == SOLD) { System.out.println("A gumball comes rolling out the slot"); count = count - 1; if (count == 0) { System.out.println("Oops, out of gumballs!"); state = SOLD_OUT; } else { state = NO_QUARTER; } } elseif (state == NO_QUARTER) { System.out.println("You need to pay first"); } elseif (state == SOLD_OUT) { System.out.println("No gumball dispensed"); } elseif (state == HAS_QUARTER) { System.out.println("No gumball dispensed"); } }
publicclassGumballMachine{ State soldOutState; State noQuarterState; State hasQuarterState; State soldState;
State state; int count = 0;
publicGumballMachine(int numberGumballs){ soldOutState = new SoldOutState(this); noQuarterState = new NoQuarterState(this); hasQuarterState = new HasQuarterState(this); soldState = new SoldState(this);
this.count = numberGumballs; if (numberGumballs > 0) { state = noQuarterState; } else { state = soldOutState; } }
voidreleaseBall(){ System.out.println("A gumball comes rolling out the slot..."); if (count > 0) { count = count - 1; } }
intgetCount(){ return count; }
voidrefill(int count){ this.count += count; System.out.println("The gumball machine was just refilled; its new count is: " + this.count); state.refill(); }
voidsetState(State state){ this.state = state; } public State getState(){ return state; }
public State getSoldOutState(){ return soldOutState; }
public State getNoQuarterState(){ return noQuarterState; }
public State getHasQuarterState(){ return hasQuarterState; }
public State getSoldState(){ return soldState; } }