Sponsors

Thursday, July 1, 2010

Command Design Pattern

When two objects communicate, often one object is sending a command to the other object to perform a particular function. The most common way to accomplish this is for the first object (the "issuer") to hold a reference to the second (the "recipient"). The issuer executes a specific method on the recipient to send the command.

But what if the issuer is not aware of, or does not care who the recipient is? That is, the issuer simply wants to abstractly issue the command?

The Command design pattern encapsulates the concept of the command into an object. The issuer holds a reference to the command object rather than to the recipient. The issuer sends the command to the command object by executing a specific method on it. The command object is then responsible for dispatching the command to a specific recipient to get the job done.

Note the similarities between the Command design pattern and the Strategy design pattern.

In the above diagram, the invoker holds an abstract command and issues a command by calling the abstract execute() method. This command is translated into a specific action on a specific receiver by the various concrete command objects. It is also possible for a command to be a collection of commands, called a "macro" command. Calling the execute method of a macro command will invoke a collection of commands.

No comments:

Post a Comment