Command pattern

commandPattern

Command pattern

Another design pattern it is very popular.I’s used inter alia in approach CQRS (for more information about CQRS).
What is command pattern and when to use it:
Sometimes, you don’t want to do execute your functions immediately.You can use the Command pattern to add work to a queue, to be done later. You can use it to retry, if a command cannot execute properly. You might be able to use this to add “undo” capabilities to a program.
commandpattern
Source: Here

Invokerthe object that executes commands by calling execute() on the object passed to it.

Commandinterface that defines the operations that must support each command (to perform tasks, rollbacks etc.).

Concrete commandclass providing implementation of the interface command, focusing on serving a single task.

Reciever receives the results of the command action

Example

Our example will be a program consisting of a trainer who gives command to sportsmans.

Let’s write an interface to our commands.It has two methods execute() and undo()

And our concrete commands.

Running:

Jumping:

And workout at the gym:

Our reciver is sportsperson, issued commands will affect on him.

Class Trener is the invoker. Adds specific commands and then execute operations on them in the order they were added and can also remove some training.

Let’s see how it’s works.

Trainer will work out a training plan for the two sportsmans and then tells them to do it. And next he removing the specific training, in this case workout at the gym.

 Result:
command pattern

Summary

If we add to this pattern – dependency injection. We get nicely composed applications eg. CQRS.

Link to the projekt HERE

One Comment on “Command pattern”

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *