diff --git a/README.md b/README.md index 98cb824..4ba910d 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,8 @@ objects). - [Flyweight], storage costs of objects - [Proxy], how an object is accessed (its location) - Behavioral Patterns - - [Chain of Responsibility], todo - - [Command], todo + - [Chain of Responsibility], object that can fulfill a request + - [Command], when and how a request is fulfilled - [Interpreter], todo - [Iterator], todo - [Mediator], todo diff --git a/command/Command.cpp b/command/Command.cpp new file mode 100644 index 0000000..1ab3c33 --- /dev/null +++ b/command/Command.cpp @@ -0,0 +1,99 @@ +/* + * C++ Design Patterns: Commnand + * Author: Jakub Vojvoda [github.com/JakubVojvoda] + * 2016 + * + * Source code is licensed under MIT licence + * (for more details see LICENCE) + * + */ + +#include + +/* + * Receiver + * knows how to perform the operations associated + * with carrying out a request + */ +class Receiver { +public: + void action() { + std::cout << "Receiver: execute action" << std::endl; + } + // ... +}; + +/* + * Command + * declares an interface for all commands + */ +class Command { +public: + virtual ~Command() {} + virtual void execute() = 0; + // ... + +protected: + Command() {} +}; + +/* + * Concrete Command + * implements execute by invoking the corresponding + * operation(s) on Receiver + */ +class ConcreteCommand : public Command { +public: + ConcreteCommand(Receiver *r) + : receiver(r) {} + + ~ConcreteCommand() { + if (receiver) { + delete receiver; + } + } + + void execute() { + receiver->action(); + } + // ... + +private: + Receiver *receiver; + // ... +}; + +/* + * Invoker + * asks the command to carry out the request + */ +class Invoker { +public: + void set(Command *c) { + command = c; + } + + void confirm() { + if (command) { + command->execute(); + } + } + // ... + +private: + Command *command; + // ... +}; + + +int main() +{ + Receiver receiver = Receiver(); + ConcreteCommand command = ConcreteCommand(&receiver); + + Invoker invoker = Invoker(); + invoker.set(&command); + invoker.confirm(); + + return 0; +} diff --git a/command/README.md b/command/README.md new file mode 100644 index 0000000..e7b770a --- /dev/null +++ b/command/README.md @@ -0,0 +1,13 @@ +## Command + +Command pattern encapsulates a request as an object, thereby letting you parameterize +clients with different requests, queue or log requests, and supports undoable +operations. The pattern has a behavioral purpose and deals with relationships between objects. + +### When to use + +* want to parameterize objects by an action to perform +* want to specify, queue, and execute requests at different times +* support undo +* support logging changes so that they can be reapplied in case of a system crash +* structure a system around high-level operations built on primitives operations