Chapter 11. Commands

Table of Contents

Command and BaseCommand
Predefined Commands
Independent Windowing Toolkit Commands
Swing Commands
SWT Commands
Creating Custom Commands
Excluding Default Commands

Command and BaseCommand

By encapsulating a request as an object, commands let you parameterize clients with different requests, queue or log requests, and support undo/redo operations.

The Command interface is one implementation of the well-known GoF pattern just described. Our Command objects are identified, described, executable objects with an enabling state that can be controlled by client code. These characteristics are reflected in the declared methods of the interface. Commands can be attached to both MenuBar and ToolBar items and generally facilitate the extension of custom applications.

All commands have these common characteristics and abilities:

  • a unique identifier

  • a description (optional)

  • a perform description (optional)

  • a perform(Object) method

The identifier is used to look up the object in the CommandRegistry and has to be unique. The behavior of a Command is coded in the perform(Object) method of an implementation class. If a description has been set and the Command is used in a ToolBar, this description will be shown as a Tooltip. The perform description describes what the Command is doing during its execution. This string is shown in the StatusBar for a short period of time.

Abstract class BaseCommand is the common base class for all of our Command implementation classes because it consolidates shared code and provides a number of overloaded constructors that make subclasses easier to write. Because this class automatically registers itself with an instance of CommandRegistry, subclasses only have to override the method perform(Object).

To make these guidelines more clear, the next section provides code examples and describes in detail how to implement your own Command classes.