Command Pattern

The Command pattern: turning a request into an object that can be queued, logged or undone, and what each command must remember to undo itself.

  • 9 cards
  • 4 questions
  • About 18 min
  • Intermediate to Advanced
Share

An editor's undo button, a queue of jobs waiting for a worker, and a remote control whose buttons can be reassigned all need the same thing: a request that exists as a value before it runs. The Command pattern turns a request into an object with a method to carry it out, so the code that triggers it can store it, pass it on, run it later, or ask it to reverse itself.

This topic opens on a button tied to the code it runs, then reads the participants off the class diagram and follows one press through a sequence diagram. The template runs two commands through an invoker that keeps a history, and undoes one, in Python, Java and TypeScript.

Two examples follow: undo in a text editor, traced through its history stack, and Java's ExecutorService, where a task is a command that is queued rather than undone. A comparison shows functools.partial doing a command's job in Python, and what it cannot do. The gotcha is an undo with nothing to restore, and the exercise builds a smart home remote with an undo button.

By the end you can recognise a command, implement one with undo, and say what it must store to reverse itself.

Contents

9 cardsnot started