Command pattern

1. Usage

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

The purpose of the Command pattern is to decouple an event generator (the Invoker) from the event handler (the Receiver). A ConcreteCommand class (sub-classed from Command) defines an execute ()method which calls the appropriate method on the Receiver (the action method). The client is responsible for associating the Receiver with the Command and then the Command with an Invoker.
N.B. 1:1:1 mapping between Invoker, Command and Receiver.

2. UML class diagram

3. Pros

decouples Invoker from Receiver – makes Receiver more re-usable as it doesn’t manage the relationship with the Invoker

Command encapsulate a request – requests can be stored so they can be undone, processed at a later time, etc.

extensible – easy to add new Commands

macros – commands can be grouped into macros so that multiple commands can be run at once