Monday, April 23, 2007

Command

In GUI applications, it is always desirable to implement the same function via different ways (e.g. menus, context menus and etc.). Hence how can it be possible to separate the invoker and commands themselves in order to avoid unnecessary repeatition of code? The Command pattern provides us more than this.

In this figure, all Commands have the same interface. Each Invoker responds to the Client by sending request to the corresponding ConcreteCommand. The Command then carries out the action to handle the request.

We can maintain a queue for Commands, and the Command should keep all necessary information to undo the action. Thus by adding an Unexecute() to the interface and implementing it in subclasses, a do/undo/redo mechanism can be established.

The advantages are:
  • It decouples the invoker and receiver and they can be modified separately.
  • A Composite of Commands can be built to represent a series of complicated operations.
  • It is easy to add new Commands.

No comments: