From cf35b0c37c4e0dc0249d298cc7f1fe11a35dfa75 Mon Sep 17 00:00:00 2001 From: Ian Dinwoodie Date: Sun, 19 May 2019 18:20:38 -0400 Subject: [PATCH] Added command example. --- README.md | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 119 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 53f7e46..5fade3e 100644 --- a/README.md +++ b/README.md @@ -1876,7 +1876,125 @@ parameters. #### Programmatic Example -TODO +First of all we have the receiver that has the implementation of every action +that could be performed. + +```cpp +// The receiver. +class Bulb +{ + public: + void turnOn(void) + { + std::cout << "Bulb has been lit." << std::endl; + } + + void turnOff(void) + { + std::cout << "Darkness!" << std::endl; + } +}; +``` + +Then we have an interface that each of the commands are going to implement and +then we have a set of commands. + +```cpp +class Command +{ + public: + virtual void execute(void) = 0; + virtual void undo(void) = 0; + virtual void redo(void) = 0; +}; + +// A command. +class TurnOn : public Command +{ + public: + TurnOn(std::shared_ptr bulb) + : bulb_(bulb) + { + } + + void execute(void) + { + bulb_->turnOn(); + } + + void undo(void) + { + bulb_->turnOff(); + } + + void redo(void) + { + execute(); + } + + private: + std::shared_ptr bulb_; +}; + +// Another command. +class TurnOff : public Command +{ + public: + TurnOff(std::shared_ptr bulb) + : bulb_(bulb) + { + } + + void execute(void) + { + bulb_->turnOff(); + } + + void undo(void) + { + bulb_->turnOn(); + } + + void redo(void) + { + execute(); + } + + private: + std::shared_ptr bulb_; +}; +``` + +Then we have an invoker with whom the client will interact to process any +commands. + +```cpp +// The invoker. +class RemoteControl +{ + public: + void submit(std::shared_ptr command) + { + command->execute(); + } +}; +``` + +Here is how this can be used: + +```cpp +std::shared_ptr bulb = std::make_shared(); + +std::shared_ptr turnOn = std::make_shared(bulb); +std::shared_ptr turnOff = std::make_shared(bulb); + +RemoteControl remote; +remote.submit(turnOn); +remote.submit(turnOff); +// Output: +// Bulb has been lit. +// Darkness! +``` Command pattern can also be used to implement a transaction based system. Where you keep maintaining the history of commands as soon as you execute them. If the