-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathState.cpp
93 lines (63 loc) · 2.16 KB
/
State.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
#include "State.h"
namespace State_Pattern_Tests {
State::State(CString name) : name(name) {
}
const String State::GetName() const noexcept {
return this->name;
}
StateContext::StateContext(std::unique_ptr<IState> state): state(state.release()) {
}
void StateContext::Freeze() {
std::cout << "Freezing " << state->GetName() << "..." << std::endl;
this->state->Freeze(this->shared_from_this());
}
void StateContext::Heat() {
std::cout << "Heating " << state->GetName() << "..." << std::endl;
this->state->Heat(this->shared_from_this());
}
void StateContext::SetState(std::unique_ptr<IState> state) noexcept {
std::cout << "Chaging state from " << this->state->GetName() << " to " << state->GetName() << "..." << std::endl;
this->state.reset(state.release());
}
std::unique_ptr<IState> StateContext::GetState() noexcept {
return std::move(this->state);
}
StateContext::~StateContext() {
// delete this->state;
std::cout << "Destroing stata " << this->state->GetName() << std::endl;
}
SolidState::SolidState() : State("Solid") {
}
void SolidState::Freeze(std::shared_ptr<StateContext> context) {
std::cout << "Nothing happens" << std::endl;
}
void SolidState::Heat(std::shared_ptr<StateContext> context) {
context->SetState(std::make_unique<LiquidState>());
}
LiquidState::LiquidState(): State("Liquid") {
}
void LiquidState::Freeze(std::shared_ptr<StateContext> context) {
context->SetState(std::make_unique<SolidState>());
}
void LiquidState::Heat(std::shared_ptr<StateContext> context) {
context->SetState(std::make_unique<GasState>());
}
GasState::GasState() : State("Gas") {
}
void GasState::Freeze(std::shared_ptr<StateContext> context) {
context->SetState(std::make_unique<LiquidState>());
}
void GasState::Heat(std::shared_ptr<StateContext> context) {
std::cout << "Nothing happens" << std::endl;
}
void Test()
{
std::shared_ptr<StateContext> sc = std::make_shared<StateContext>(std::make_unique<SolidState>());
sc->Heat();
sc->Heat();
sc->Heat();
sc->Freeze();
sc->Freeze();
sc->Freeze();
}
}