-
Notifications
You must be signed in to change notification settings - Fork 1
/
command-pattern.cc
95 lines (87 loc) · 1.88 KB
/
command-pattern.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
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
#include <iostream>
#include <vector>
#include <initializer_list>
class Network {
bool state = false;
public:
void on() {
if (!state) {
state = true;
std::cout << "Network has been connected.\n";
}
}
};
struct WeChatService {
void sendMessage(const std::string& msg = "") {
std::cout << "WeChatService is sending message: "
<< msg << '\n';
}
};
struct WeatherService {
void forecast() {
std::cout << "Weather forecast: "
<< "It's sunny in the following 24 hours.\n";
}
};
struct Command {
virtual void execute() = 0;
virtual ~Command() {}
};
class WeatherForecastCommand : public Command {
Network& network;
WeatherService& weather;
public:
WeatherForecastCommand(
Network& network,
WeatherService& weather)
: network(network), weather(weather) {}
void execute() override {
network.on();
weather.forecast();
}
};
class WeChatServiceCommand : public Command {
const std::string& msg;
Network& network;
WeChatService& wechat;
public:
WeChatServiceCommand(
const std::string& msg,
Network& network,
WeChatService& wechat)
: msg(msg), network(network), wechat(wechat) {}
void execute() override {
network.on();
wechat.sendMessage(msg);
}
};
class Shortcut {
std::vector<Command*> commands;
public:
Shortcut(std::initializer_list<Command*> commands)
: commands(commands) {}
void addCommand(Command* cmd) {
commands.push_back(cmd);
}
void run() {
for (const auto& cmd : commands) {
cmd->execute();
}
}
};
int main() {
Network network;
WeChatService wechat;
WeatherService weatherService;
WeChatServiceCommand weChatMessageCommand {
"Hello, world!", network, wechat
};
WeatherForecastCommand weatherForecastCommand {
network, weatherService
};
Shortcut shortcut {
&weChatMessageCommand,
&weatherForecastCommand,
};
shortcut.run();
}