-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.cc
60 lines (50 loc) · 1.09 KB
/
state.cc
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
//
// Design pattern # state
// Lets an object alter its behavior when its
// internal state changes.
//
// g++ -std=c++17 -Wall -Wextra -o state state.cc
//
#include <iostream>
struct State {
virtual void write(std::string text) = 0;
};
struct UpperCase: State {
void write(std::string text) override {
for (auto ch: text) {
std::cout << static_cast<char>(std::toupper(ch));
}
std::cout << '\n';
}
};
struct LowerCase: State {
void write(std::string text) override {
for (auto ch: text) {
std::cout << static_cast<char>(std::tolower(ch));
}
std::cout << '\n';
}
};
struct TextEditor {
State *state;
TextEditor(State *state) {
this->state = state;
}
void write(std::string text) {
this->state->write(text);
}
void set_state(State *new_state) {
this->state = new_state;
}
};
//
// Entry function
//
int main() {
std::cout << "Design pattern # state\n";
TextEditor *editor = new TextEditor(new LowerCase());
editor->write("Sample Text to Write");
editor->set_state(new UpperCase());
editor->write("More text");
return 0;
}