-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcommand.cpp
More file actions
124 lines (98 loc) · 2.58 KB
/
command.cpp
File metadata and controls
124 lines (98 loc) · 2.58 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Command design pattern
#include <cstddef>
#include <iostream>
// device interface (receivers)
class IDevice {
protected:
bool is_on_ = false;
std::size_t volume_ = 0;
public:
virtual void on() = 0;
virtual void off() = 0;
virtual void up() = 0;
virtual void down() = 0;
virtual ~IDevice() = default;
bool is_on() const { return is_on_; }
std::size_t get_volume() const { return volume_; }
};
// command interface
class ICommand {
protected:
IDevice& device_;
public:
ICommand(IDevice& device) : device_{device} {}
virtual void execute() = 0;
virtual void undo() = 0;
virtual ~ICommand() = default;
};
// devices
class TV : public IDevice {
void on() override {
is_on_ = true;
std::cout << "TV is ON\n";
}
void off() override {
is_on_ = false;
std::cout << "TV is OFF\n";
}
void up() override {
if (volume_ < 10) {
++volume_;
}
std::cout << "Turning volume up to " << volume_ << '\n';
}
void down() override {
if (volume_ > 0) {
--volume_;
}
std::cout << "Turning volume down to " << volume_ << '\n';
}
};
// commands
class Turn_ON : public ICommand {
public:
using ICommand::ICommand;
void execute() override { device_.on(); }
void undo() override { device_.off(); }
};
class Turn_OFF : public ICommand {
public:
using ICommand::ICommand;
void execute() override { device_.off(); }
void undo() override { device_.on(); }
};
class Turn_UP : public ICommand {
public:
using ICommand::ICommand;
void execute() override { device_.up(); }
void undo() override { device_.down(); }
};
class Turn_DOWN : public ICommand {
public:
using ICommand::ICommand;
void execute() override { device_.down(); }
void undo() override { device_.up(); }
};
int main() {
TV tv; // a concrete device
// some commands
Turn_ON turn_on(tv);
Turn_OFF turn_off(tv);
Turn_UP turn_up(tv);
Turn_DOWN turn_down(tv);
// execute/undo the commands
turn_on.execute(); // execute
turn_off.execute();
turn_off.undo(); // undo
turn_up.execute();
turn_up.execute();
turn_down.execute();
turn_up.undo();
turn_up.undo(); // the volume cannot be less than zero
for (std::size_t i = 0; i < 12; ++i) {
turn_up.execute(); // the volume cannot be greater than 10
}
turn_off.execute();
std::cout << "Is the TV ON? " << std::boolalpha << tv.is_on() << '\n';
std::cout << "Final TV volume: " << tv.get_volume() << '\n';
}