Sunday, November 30, 2014

Design Pattern : Command

Type : Behavioral Design Pattern


Command Pattern encapsulate request in an object which is used to invoke a method. 

Important Points

Command Pattern encapsulate request to do some operation.
Command Pattern can be used to do undo operations(Invoker).
Command Pattern decouples requestor(Invoker) of the action from the object that perform the action(Reciever).


Different  Objects participating  in the pattern are,

Command - declares an interface for executing an operation;
ConcreteCommand - extends the Command interface, implementing the execute method by invoking the corresponding operations on Receiver. It defines a link between the Receiver and the action.
Client - creates a ConcreteCommand object and sets its receiver;
Invoker - Holds Command Object and executes execute() method of the command object;
Receiver - knows how to perform the operations;

The Command Pattern is useful when:
  • A history of requests is needed
  • You need callback functionality
  • Requests need to be handled at variant times or in variant orders
  • The invoker should be decoupled from the object handling the invocation.


This example is about an Delivery agent which takes some kind of order and delivers it. 

Receiver is OrderDeliverReciever Object which knows what to perform, in this case it just print the number of orders.

Invoker is DeliveryAgentInvoker which contains all the Commands object, in this case it executes the method in Command Object.

We have two command objects OrderDeliveryAddCommand and OrderDeliveryRemoveCommand, which adds a order and removes a order respectively.

Client sets the Commands in Invoker Object  and calls method in Invoker.

Class Diagram

No comments :

Post a Comment