Command Design Pattern

COMP 310  Java Resources  Eclipse Resources

(Back to Design Patterns)

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.

Figure 1
Figure 1 (command.png)

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.

 


Originally published in Connexions (CNX): https://web.archive.org/web/20130914171626/http://cnx.org/content/m17187/latest/

 

© 2023 by Stephen Wong