-
Notifications
You must be signed in to change notification settings - Fork 55
/
state.cpp
61 lines (46 loc) · 1.26 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
#include <iostream>
#include <memory>
namespace jc {
class Connection;
class State {
public:
virtual void Open(const Connection&) const = 0;
virtual void Close(const Connection&) const = 0;
virtual ~State() = default;
};
class Connection {
public:
Connection(std::unique_ptr<State> p) : p_(std::move(p)) {}
void ChangeState(std::unique_ptr<State> p) { p_ = std::move(p); }
void Open() const { p_->Open(*this); }
void Close() const { p_->Close(*this); }
private:
std::unique_ptr<State> p_;
};
class StateA : public State {
public:
void Open(const Connection&) const override {
std::cout << "open in stateA\n";
}
void Close(const Connection&) const override {
std::cout << "close in stateA\n";
}
};
class StateB : public State {
public:
void Open(const Connection&) const override {
std::cout << "open in stateB\n";
}
void Close(const Connection&) const override {
std::cout << "close in stateB\n";
}
};
} // namespace jc
int main() {
jc::Connection connection{std::make_unique<jc::StateA>()};
connection.Open(); // open in stateA
connection.Close(); // close in stateA
connection.ChangeState(std::make_unique<jc::StateB>());
connection.Open(); // open in stateB
connection.Close(); // close in stateB
}