Command Pattern

We have all visited doctors at some point in our life. After due checkup, the doctor diagnosed the disease and prescribed some pills that we obtained from the pharmacy. The pharmacist hands over the pills that we need - his job ends there. The way we consume the pills barely depends upon what they contain - we just gulp them down with a glass of water - this process remains unchanged irrespective of what those pills contain. Everything works if the prescription was good.

This is command pattern. It decouples an object that invokes the operation from the one that actually performs it. Thus, we have two modules - one that knows how the command should be invoked and other that knows how it should be implemented. The command pattern ensures a good decoupling between the two.

This is achieved by defining a Command interface with an execute() method taking relevant parameters (the medical pill in our case). A concrete implementation of this Command interface is instantiated by the client (the pharmacist) and handed over to the Invoker (the patient) - that actually triggers the execute method when prescribed. This works well if the designer (the doctor) has coordinated things correctly.

All clients of Command objects treat it as a "black box" by simply invoking the object’s virtual execute() method whenever the client requires the object's "service". A Command class holds some subset of the following: an object, a method to be applied to the object, and the arguments to be passed when the method is applied. The Command's "execute" method then causes the pieces to come together.

Sequences of Command objects can be assembled into composite (or macro) commands.

Thus, the participants in the command pattern are:

  • Command - Declares an interface for executing an operation.
  • ConcreteCommand - Defines a binding between a Receiver object and an action. Implements Execute by invoking the corresponding operation(s) on Receiver.
  • Client - Creates a ConcreteCommand object and sets its receiver.
  • Invoker - Asks the command to carry out the request.
  • Receiver - Knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.