-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstate.cpp
65 lines (54 loc) · 1.75 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
// State design pattern
#include <algorithm>
#include <cctype>
#include <iostream>
#include <memory>
#include <string>
// state interface
struct IState {
virtual void write(class Type_Writter& type_writter, std::string what) = 0;
virtual ~IState() = default;
};
// context, we model a type writter with 2 states: Caps ON and Caps OFF
// that keep switching automatically
class Type_Writter {
protected:
std::unique_ptr<IState> state_;
public:
Type_Writter(std::unique_ptr<IState> state) : state_{std::move(state)} {}
void set_state(std::unique_ptr<IState> state) { state_ = std::move(state); }
void write(const std::string& what) { state_->write(*this, what); }
};
// concrete states
class Caps_ON : public IState {
public:
void write(Type_Writter& type_writter, std::string what) override;
};
class Caps_OFF : public IState {
public:
void write(Type_Writter& type_writter, std::string what) override;
};
// implementation of concrete states
void Caps_ON::write(Type_Writter& type_writter, std::string what) {
std::transform(std::begin(what), std::end(what), std::begin(what),
::toupper);
std::cout << what;
}
void Caps_OFF::write(Type_Writter& type_writter, std::string what) {
std::transform(std::begin(what), std::end(what), std::begin(what),
::tolower);
std::cout << what;
}
int main() {
// the context
Type_Writter type_writter{std::make_unique<Caps_OFF>()};
// the state machine in action
type_writter.write("Hello ");
type_writter.write("World!\n");
// switch the state
type_writter.set_state(std::make_unique<Caps_ON>());
type_writter.write("This ");
type_writter.write("is ");
type_writter.write("a ");
type_writter.write("test.\n");
}