Design Pattern

Command Design Pattern

Introduced in CS247.

The Command Design Pattern is about using objects to encapsulate behavior of some “action” with a system.

When to use Command Pattern

Have classes that represent an “action” or “command” in our program.

Example

Example: Consider writing an IDE, using MVC - we might have model/controller relationship where controller calls model methods, like:

  • Model::insert Text
  • Model::copy
  • Model::paste
  • Model::changeSyntaxHighlighting

This is a decent design - but it doesn’t allow for some features we might desire:

  • Macros - replaying sequences of instructions
  • Undo / redo

Command pattern: Instead of manipulating the model directly - pass commands to an invoker

Command object has whatever information it needs to perform its given action - maybe model, maybe subjects within the model

  1. Controller would create command objects, supply with info they need
  2. Sends abstract commands to the Invoker for processing
  3. Invoker calls each action method to execute the command

Invoker can maintain additional state - stack of commands for undo / redo, or mapping of a macro keyword to a list of commands.