-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGumballMachine.java
More file actions
108 lines (90 loc) · 2.65 KB
/
GumballMachine.java
File metadata and controls
108 lines (90 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package StatePattern.FinalVersion;
public class GumballMachine {
State soldOutState;
State noQuarterState;
State hasQuarterState;
State soldState;
State winnerState;
State state = soldOutState;
int count = 0;
public GumballMachine(int numberGumballs){
soldOutState = new SoldOutState(this);
noQuarterState = new NoQuarterState(this);
hasQuarterState = new HasQuarterState(this);
soldState = new SoldState(this);
winnerState = new WinnerState(this);
this.count = numberGumballs;
if(count >0){
state = noQuarterState;
}else{
state = soldOutState;
}
}
public void insertQuarter(){
state.insertQuarter();
}
public void ejectQuarter(){
state.ejectQuarter();
}
public void turnCrank(){
state.turnCrank();
state.dispense();
}
void setState(State state){
this.state = state;
}
void releaseBall(){
System.out.println("A gumball comes rolling out the slot");
if(count != 0){
count--;
}
}
public int getCount() {
return count;
}
public void refill(int numGumballs) {
this.count += numGumballs;
if (count > 0) {
state = noQuarterState;
}
System.out.println("Refilled with " + numGumballs + " gumballs");
}
public State getSoldOutState() {
return soldOutState;
}
public State getNoQuarterState() {
return noQuarterState;
}
public State getHasQuarterState() {
return hasQuarterState;
}
public State getSoldState() {
return soldState;
}
public State getWinnerState() {
return winnerState;
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append("\nMighty Gumball, Inc.");
result.append("\nJava-enabled Standing Gumball Model #2004\n");
result.append("Inventory: " + count + " gumball");
if (count != 1) {
result.append("s");
}
result.append("\nMachine is ");
if (state == soldOutState) {
result.append("sold out");
} else if (state == noQuarterState) {
result.append("waiting for quarter");
} else if (state == hasQuarterState) {
result.append("waiting for turn of crank");
} else if (state == soldState) {
result.append("delivering a gumball");
} else if (state == winnerState) {
result.append("delivering two gumballs");
}
result.append("\n");
return result.toString();
}
}