add Command pattern

This commit is contained in:
Jakub Vojvoda
2016-09-18 19:44:57 +02:00
parent ccb84d7818
commit f17d7e90e7
3 changed files with 114 additions and 2 deletions

View File

@@ -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

99
command/Command.cpp Normal file
View File

@@ -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 <iostream>
/*
* 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;
}

13
command/README.md Normal file
View File

@@ -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