Command pattern. Implementation of a structure for two recipients. Example in C++
An example C++ program is demonstrated that implements the Command pattern for two recipients.
1. Task
Using the C++ language, you need to implement the Command pattern for two recipients, the structure of which is shown in Figure 1.
Figure 1. Command pattern. A structure for two command receivers
2. Pattern participants
Pattern participants:
- Client – the client, which in the program is the main() function;
- Command – an abstract class that represents the interface between the calling code and a specific command;
- ConcreteCommand1, ConcreteCommand2 – classes corresponding to specific commands;
- Invoker – a class that calls a specific command through a link to the Command interface;
- Receiver – a class whose object is obtained by a specific command ConcreteCommand1 or ConcreteCommand2.
3. Implementation in C++
// Command pattern #include <iostream> using namespace std; // The class that a particular command receives class Receiver { public: void Action1() { cout << "Receiver::Action1()" << endl; } void Action2() { cout << "Receiver::Action2()" << endl; } }; // class Command { public: // Operation virtual void Execute() {} protected: // Constructor Command() { } }; // Specific command execution class class ConcreteCommand1 : public Command { private: Receiver* receiver; public: // Constructor ConcreteCommand1(Receiver* _receiver) { receiver = _receiver; } void Execute() { receiver->Action1(); } }; class ConcreteCommand2 : public Command { private: Receiver* receiver; public: // Constructor ConcreteCommand2(Receiver* _receiver) { receiver = _receiver; } void Execute() { receiver->Action2(); } }; // A class that contains a method for calling a particular command. // This class stores an object of type ConcreteCommand class Invoker { private: // Command Command* command; public: // Constructor Invoker(Command* _command = nullptr) { command = _command; } // Calling the method void Invoke() { command->Execute(); } // Method that sets the command void SetCommand(Command* _command) { command = _command; } }; void main() { // Client Receiver* receiver = new Receiver; // Create commands ConcreteCommand1* command1 = new ConcreteCommand1(receiver); ConcreteCommand2* command2 = new ConcreteCommand2(receiver); // Create a calling class Invoker* invoker = new Invoker; // Menu organization int cmd; while (true) { cout << "Enter command (1-3): 1 - Command-1, 2 - Command-2, 3 - Exit" << endl; cin >> cmd; if (cmd == 1) { invoker->SetCommand(command1); invoker->Invoke(); // command1->Execute() } if (cmd == 2) { invoker->SetCommand(command2); invoker->Invoke(); // command2->Execute() } if (cmd == 3) break; } if (invoker != nullptr) delete invoker; if (command1) delete command1; if (command2) delete command2; if (receiver != nullptr) delete receiver; }
⇑