-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.cpp
89 lines (69 loc) · 1.67 KB
/
main.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
/*
* @FileName : state/main.cpp
* @CreateAt : 2022/4/19
* @Author : Inno Fang
* @Email : innofang@yeah.net
* @Description: Simple implementation of State pattern
*/
#include <iostream>
class Context;
class State {
public:
virtual ~State() {};
void setContext(Context *context) {
_context = context;
}
virtual void handle1() = 0;
virtual void handle2() = 0;
protected:
Context *_context;
};
class Context {
public:
~Context() {
delete _state;
}
void setState(State *state) {
delete _state;
_state = state;
_state->setContext(this);
}
void request1() {
_state->handle1();
}
void request2() {
_state->handle2();
}
private:
State *_state;
};
class ConcreteStateA : public State {
public:
void handle1() override;
void handle2() override {
std::cout << "ConcreteStateA handles request2.\n";
}
};
class ConcreteStateB : public State {
public:
void handle1() override {
std::cout << "ConcreteStateB handles request1.\n";
}
void handle2() override {
std::cout << "ConcreteStateB handles request2.\n";
std::cout << "ConcreteStateB wants to change the state of the context.\n";
_context->setState(new ConcreteStateA);
}
};
void ConcreteStateA::handle1() {
std::cout << "ConcreteStateA handles request1.\n";
std::cout << "ConcreteStateA wants to change the state of the context.\n";
_context->setState(new ConcreteStateB());
}
int main() {
Context *context = new Context();
context->setState(new ConcreteStateA);
context->request1();
context->request2();
return 0;
}