CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

The idea

Wrap the call in a thing you can hold.

Think of a restaurant order slip. The customer does not walk into the kitchen and tell the chef what to cook. A waiter writes the order on a slip. The slip can wait on a spike, be handed to a chef, be copied for the till, or be crossed out if the customer changes their mind. The slip is the request, written down as a thing.

GoF's intent for Command is to wrap a request in an object, so that clients can be set up with different requests, requests can be queued or logged, and operations can be undone. GoF's motivation is a toolkit with buttons and menus. The toolkit cannot hard-code what a menu item does, since only the application knows. So each menu item holds a command object, and when clicked, it asks the command to run.

GoF lists when to use it.

  • To set an object up with an action to perform, in the way a callback does in a procedural language. Commands are the object-oriented replacement for callbacks.
  • To specify, queue and run requests at different times. A command can outlive the request that created it.
  • To support undo, by letting execute store what it needs to reverse itself, and adding an undo operation. A history list gives many levels of undo and redo.
  • To keep a log of changes so that they can be replayed after a crash.
  • To build high-level operations such as transactions from small steps.

Command pattern

The Command pattern turns a request into an object that holds everything needed to carry it out, so the request can be stored, passed, delayed, repeated or reversed.

Example: a Book object that knows the schedule and the slot, and can run or undo the booking.

Check yourself: 1. In the order slip picture, what is the command? 2. Name three things GoF lists as reasons to use Command. 3. What does a command need to support undo?