Command pattern is a behavioral pattern in GoF as it allows us to decouple between the Invoker (a.k.a. sender, an object that invokes an operation) and the Receiver (an object that receives the request to execute a certain operation).

overview

Command, an interface that encapsulate the request itself, promotes "invocation of a method on an object" via an Execute() method. Each concrete Command class provides different Execute() implementations to invoke the request, and contains a Receiver as an instance variable by which the request will be carried out. An optional Unexecute() method can be added to the Command for undo operations to reverse the effects of a preceding Execute operation using whatever undo information Execute stored. ​Command is implemented as an Adaptor between Invoker and Receiver.

Invoker, an aggregation of Commands, asks the command to carry out the request. In the above figure, MenuItem is the Invoker. The Switch class as seen in our code example below is also an Invoker. An Invoker invokes command.Execute() operation.

Receiver, encapsulated by Command, knows how to carry out a request. Any class may serve as a Receiver. In the above figure, Document and Application are the Receivers.

The decoupling between the Invoker/Sender and the Receiver is achieved by the Command served as an Adaptor between the Invoker and the Receiver. Specifically, Invoker contains Commands, each Command in terms contains a Receiver.