Command.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: COMMAND
  4. * http://www.plantuml.com/plantuml/uml/PP7DIiD058NtynGNN5IhCRWj8THM5ovQGTpBP79AH-Sdp4-mg0_aS_XYfkaaQhra4SxzxZadPEu3To5gnV89BUzNg-lr3KrorezGt7kwCwrzWQCtHjrar3ZPye0dORNcfkxLS_88ouDmUfOal4B4W1_vOx1yW81ia-SUvI98Qmw8D05kmmKeNIRgP33yxRIqHZYC8VzAkfIKSluuR6KDWcx2ZZHq1USPOyFNJhDio6TZtIoR7YUoumRPUpaUCcC3Y7jQN_K5YgeiX5NMpPpTSRLG4MLYYxnVb4LUbGFxk6imsmkqm9QtqZgk-jsj4RpnKO6Y0QKV0QgvyPr2jdf6kEZ9-kjJsDXqPFS89M42rP4sDZeZlKTqbmnTwtrHDk_UebRV
  5. *
  6. */
  7. #include <iostream>
  8. class Receiver {
  9. public:
  10. void action() {
  11. std::cout << "Receiver: execute action" << std::endl;
  12. }
  13. Receiver() { std::cout << "Constructor Receiver" << std::endl; }
  14. };
  15. class Command {
  16. public:
  17. virtual ~Command() {}
  18. virtual void execute() = 0;
  19. };
  20. class ConcreteCommand : public Command {
  21. public:
  22. ConcreteCommand(Receiver *r) : private_receiver(r) {std::cout << "Constructor ConcretCommand" << std::endl; };
  23. ~ConcreteCommand() {
  24. if (!private_receiver) {
  25. delete private_receiver;
  26. }
  27. }
  28. void execute() {
  29. std::cout << "ConcreteCommand execute" << std::endl;
  30. private_receiver->action();
  31. }
  32. private:
  33. Receiver* private_receiver;
  34. };
  35. class Invoker {
  36. public:
  37. void setCommand(Command* c) {
  38. private_command = c;
  39. }
  40. void executeCommand() {
  41. std::cout << "Invoker: executeCommand" << std::endl;
  42. if (private_command) private_command->execute();
  43. }
  44. private:
  45. Command* private_command;
  46. };
  47. int main() {
  48. Receiver* receiver = new Receiver();
  49. Command *command = new ConcreteCommand(receiver);
  50. Invoker invoker;
  51. invoker.setCommand(command);
  52. invoker.executeCommand();
  53. }