The Command design pattern describes how a client object can invoke behavior in the rest of the system without itself knowing the semantics of that behavior. A command thus represents semantic-less abstract behavior to its client.
A client object holds a variable of type ICommand, which is a reference to an object that implements that interface. In the above diagram, any instantiation of the classes CommandA, CommandB or CommandC could validly be assigned to the iCommand variable in a ClientA object. Usually the commands are instantiated elsewhere in the system and handed to the client object at run time.
The client simply knows that at a certain point in its computations, a behavior of some sort needs to be invoked. The client does not know what that behavior is, only when it needs to be invoked.
Commands are very good a decoupling parts of a system. If a client doesn't need to know exactly what a certain behavior is, then the command design pattern will free it from having to know, thus reducing its dependencies on the rest of the system.
Example: Status logging
At various points in a system, it is often useful to log the state of the system during diagnostic processes of the system. However, the user may wish for the status logging to go to a number of different places, such as the hard disk, the screen, a printer or a remote server. And when the system is not being diagnosed, there may be no need for any logging.
Putting multi-way conditionals to determine which type of logging to do at every logging point in the code causes unnecessary code bloat, plus may cause performance problems. In addition, if the manner of logging is changed, then the entire codebase must be searched and updated. This could be an extremely complex problem in a large system.
Instead, at each logging point, simply execute a command, passing the command the local status. To change the type of logging used, the user simply needs to change the concrete command object assigned to the command variable that is being used by the rest of the system. This can be done at run-time via radio buttons on the GUI or the like. To turn off logging, one simply needs to assign the command variable to a command object whose apply() method does a no-operation. This code is much more robust, flexible, extensible and provably correct than the procedural alternative described above.
For more informations please see the page in the Java Resources web site:
http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/command.htm
The code that was demonstrated in the workshop is here: ICommand.java and IntList.java
The UML diagram for the above code: