-
Notifications
You must be signed in to change notification settings - Fork 0
/
GumballMachine.cpp
120 lines (103 loc) · 2.02 KB
/
GumballMachine.cpp
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
109
110
111
112
113
114
115
116
117
118
119
120
#include "GumballMachine.h"
#include "NoQuarterState.h"
#include "HasQuarterState.h"
#include "SoldOutState.h"
#include "SoldState.h"
#include "WinnerState.h"
#include <iostream>
#include <memory>
#include <ostream>
class State;
GumballMachine::GumballMachine(int numberOfBalls)
: soldOutState(std::make_unique<SoldOutState>(this)),
noQuarterState(std::make_unique<NoQuarterState>(this)),
hasQuarterState(std::make_unique<HasQuarterState>(this)),
soldState(std::make_unique<SoldState>(this)),
winnerState(std::make_unique<WinnerState>(this)),
count(numberOfBalls)
{
state = (count > 0) ? noQuarterState.get() : soldOutState.get();
}
void
GumballMachine::insertQuarter()
{
state->insertQuarter();
}
void
GumballMachine::ejectQuarter()
{
state->ejectQuarter();
}
void
GumballMachine::turnCrank()
{
state->turnCrank();
state->dispense();
}
void
GumballMachine::releaseBall()
{
std::cout << "A gumball comes rolling out the slot...\n";
if (count > 0)
--count;
}
int
GumballMachine::getCount() const
{
return count;
}
void
GumballMachine::refill(int c)
{
count += c;
std::cout << "The gumball machine was just refilled; its new count is: "
<< count << '\n';
state->refill();
}
void
GumballMachine::setState(State *s)
{
state = s;
}
State*
GumballMachine::getState() const
{
return state;
}
State*
GumballMachine::getNoQuarterState() const
{
return noQuarterState.get();
}
State*
GumballMachine::getHasQuarterState() const
{
return hasQuarterState.get();
}
State*
GumballMachine::getSoldOutState() const
{
return soldOutState.get();
}
State*
GumballMachine::getSoldState() const
{
return soldState.get();
}
State*
GumballMachine::getWinnerState() const
{
return winnerState.get();
}
std::ostream&
operator<<(std::ostream &os, const GumballMachine &gbm)
{
os << "\nMighty Gumball, Inc.";
os << "\nC++ enabled Standing Gumball Model #2020";
os << "\nInventory: " << gbm.getCount() << " gumball";
if (gbm.getCount() != 1)
os << "s";
os << "\n";
os << "Machine is " << *gbm.getState() << "\n";
return os;
}