From 0d7fb0f8785a06e900bd7c6017e122ed6cd0b22e Mon Sep 17 00:00:00 2001 From: Ian Dinwoodie Date: Sun, 19 May 2019 18:20:44 -0400 Subject: [PATCH] Added command example source code. --- examples/behavioral/command.cpp | 108 ++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 examples/behavioral/command.cpp diff --git a/examples/behavioral/command.cpp b/examples/behavioral/command.cpp new file mode 100644 index 0000000..2041dc3 --- /dev/null +++ b/examples/behavioral/command.cpp @@ -0,0 +1,108 @@ +#include +#include + +// The receiver. +class Bulb +{ + public: + void turnOn(void) + { + std::cout << "Bulb has been lit." << std::endl; + } + + void turnOff(void) + { + std::cout << "Darkness!" << std::endl; + } +}; + +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_; +}; + +// The invoker. +class RemoteControl +{ + public: + void submit(std::shared_ptr command) + { + command->execute(); + } +}; + +int main() +{ + 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! + + return 0; +}