teacher
Sign in

Command

Turn an action into an object so it can be queued, logged, undone and redone, with a text editor as the worked example.

25 min3 interactive1 problems

The problem it solves

A button, a menu item and a keyboard shortcut all say "delete the last word". If each calls the document directly, three places know how to delete. Worse, once the call returns, the action is gone: nothing remembers what happened, so there is no undo.

Command wraps one action, with everything it needs, in an object:

  • execute() does it.
  • undo() reverses it.

Once an action is an object you can store it, pass it around, run it later, run it again, or throw it away. That gives you:

  • Undo and redo: keep the objects on a stack.
  • Queues and schedulers: run jobs later, on another thread.
  • Logs and retries: record what ran, replay it after a crash.
  • Macros: group several commands into one.
1 of 8