Separating Requests from Execution with Command Processor

When you're building a system that has multiple commands, the system can become unwieldy if each command is handled separately. When a command is triggered by an external (or internal) event, some large switchlike functionality usually routes the event to the correct command. When new commands are added to the system, both the new command code and the event-routing functionality must change. It's even worse when the arguments or parameters of a command change, because then you must find every place in the code that refers to the command and change it — a maintenance headache.

The Command Processor design pattern offers a better, easier way to add or delete commands. A ComProcessor is the manager of the actual commands and oversees their functions; it also provides the framework for including undo mechanisms.

Looking inside the pattern structure

Five classes are involved in the Command Processor design pattern:

  • The AbstractCommand superclass and the ComObj classes implement the interfaces of the command.
  • The Controller and ComProcessor classes manage command execution.
  • Individual objects of the fifth class type, Supplier, do the actual work required for the commands to succeed.

Figure 20-1 shows how all these classes fit together into the system.

images

Figure 20-1: Class diagram for the Command Processor pattern.

Making a family ...

Get Pattern-Oriented Software Architecture For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.