Command Pattern


Problem


We need to be able to issue requests to objects without knowing anything about how the requested operation is implemented or anything about the receiver of the request.

Solution


Issue requests by sending an object (or a representation of one to the receiver. That way we can plug different receivers in easily, just making sure they will understand the request.

Related Patterns


  • Observer
  • Chain of Responsibility
  • Memento (mementos can be used to maintain the state for undo operations)

Discussion


By sending the request as an object, we will be able to undo the operation easily. The purpose of the Command pattern is twofold: to separate interface and time: the requester is isolated from the requestee and the response doesn't always need to be completed immediately.

Examples


Encapsulating requests as objects is the Command pattern. The check at a restaurant is an example of the Command pattern. A member of the wait staff takes a command (the customer's food order) and stores that by writing it on the check. The order is then queued in the kitchen to be prepared. The request object (check) is not necessarily dependent on the menu, and therefore can support commands to cook many different items with many variations.

Code


We separate the request as a Command object and pass it to foo and bar.

interface Command{ void execute();}

static class foo implements Command{
  public void execute(){
    System.out.println("quux");
  }
}
static class bar implements Command{
  public void execute(){
    System.out.println("baz");
  }
}

public static List generateRequests(){
  List queue = new ArrayList();
  queue.add(new foo());
  queue.add(new bar());
  return queue;
}
public static void doRequests(List queue){
  for(Iterator iter = queue.iterator(); it.hasNext();){
    ((Command)iter.next()).execute();
  }
}

public static void main(String[] args){
  List queue = generateRequests();
  doRequests(queue);
}
// output:
quux
baz