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