FuzzDuck
FuzzDuck
Command pattern
FuzzDuck
Command pattern

Command Pattern

The command pattern introduces a way of sending commands from one class to another without the trouble of knowing every single detail behind. As a client, you can just tell an invoker that you want certain things to be done. The invoker calls the ConcreteCommand, which handles the specific order to the receiver. The reiver gets the order specified by the ConcreteCommand done. The client gets the job done, sending only a simple command.

Command Pattern UML

Remote controller

The remote controller

Lets say you have a remote controller to signal every electronic device in your house. The controller got simple buttons, from which you can turn every device on or off. When you press the on button for the TV, the remote controller tells the TV to carry out your order. In this scenario, the controller acts as the invoker, receiving orders from the Client. After taking an order by the Client, the invoker makes a specific call or ConcreteCommand to the TV Receiver to carry out special operations.

The dog trainer

Image a scenario with a dog and a dog trainer. The dog trainer has to give various commands for the dogs to behave in a specific way. When the trainer says “fetch”, the dog is free to go fetch. When the trainer says “stop”, the dog has to freeze in place. Compared to the command pattern, the Dog is equal to the Receiver class, the trainer is equal to the invoker, and the commands “Stop” and “Fetch” are equal to the ConcreteCommand class.