-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommand Design Pattern
62 lines (50 loc) · 1.38 KB
/
Command Design Pattern
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
/*
The Command Pattern is a behavioral design pattern that focuses on encapsulating a request as an object, thereby decoupling the sender of the request from the receiver.
This pattern allows you to parameterize objects with commands, delay or queue a request’s execution, and support undoable operations.
It’s a fundamental pattern for implementing a wide range of functionality in software systems.
*/
#include <iostream>
#include <vector>
class Command {
public:
virtual void execute() = 0;
};
class Receiver {
public:
void action() {
std::cout << "Receiver action" << std::endl;
}
};
class ConcreteCommand : public Command {
private:
Receiver* receiver;
public:
ConcreteCommand(Receiver* receiver) : receiver(receiver) {}
void execute() override {
receiver->action();
}
};
class Invoker {
private:
std::vector<Command*> commands;
public:
void addCommand(Command* command) {
commands.push_back(command);
}
void executeCommands() {
for (auto* command : commands) {
command->execute();
}
}
};
int main() {
Receiver* receiver = new Receiver();
Command* command = new ConcreteCommand(receiver);
Invoker* invoker = new Invoker();
invoker->addCommand(command);
invoker->executeCommands();
delete invoker;
delete command;
delete receiver;
return 0;
}