001package headfirst.state.gumballstatewinner;
002
003public class GumballMachine {
004
005        State soldOutState;
006        State noQuarterState;
007        State hasQuarterState;
008        State soldState;
009        State winnerState;
010
011        State state = soldOutState;
012        int count = 0;
013
014        public GumballMachine(int numberGumballs) {
015                soldOutState = new SoldOutState(this);
016                noQuarterState = new NoQuarterState(this);
017                hasQuarterState = new HasQuarterState(this);
018                soldState = new SoldState(this);
019                winnerState = new WinnerState(this);
020
021                this.count = numberGumballs;
022                if (numberGumballs > 0) {
023                        state = noQuarterState;
024                }
025        }
026
027        public void insertQuarter() {
028                state.insertQuarter();
029        }
030
031        public void ejectQuarter() {
032                state.ejectQuarter();
033        }
034
035        public void turnCrank() {
036                state.turnCrank();
037                state.dispense();
038        }
039
040        void setState(State state) {
041                this.state = state;
042        }
043
044        void releaseBall() {
045                System.out.println("A gumball comes rolling out the slot...");
046                if (count != 0) {
047                        count = count - 1;
048                }
049        }
050
051        int getCount() {
052                return count;
053        }
054
055        void refill(int count) {
056                this.count = count;
057                state = noQuarterState;
058        }
059
060        public State getState() {
061                return state;
062        }
063
064        public State getSoldOutState() {
065                return soldOutState;
066        }
067
068        public State getNoQuarterState() {
069                return noQuarterState;
070        }
071
072        public State getHasQuarterState() {
073                return hasQuarterState;
074        }
075
076        public State getSoldState() {
077                return soldState;
078        }
079
080        public State getWinnerState() {
081                return winnerState;
082        }
083
084        public String toString() {
085                StringBuilder result = new StringBuilder();
086                result.append("\nMighty Gumball, Inc.");
087                result.append("\nJava-enabled Standing Gumball Model #2004");
088                result.append("\nInventory: " + count + " gumball");
089                if (count != 1) {
090                        result.append("s");
091                }
092                result.append("\n");
093                result.append("Machine is " + state + "\n");
094                return result.toString();
095        }
096}