Skip to content

Design Patterns

Command

Running or undoing one command takes O(1) time (a constant amount). The real cost is whatever the wrapped action itself costs.

The idea, in plain English

A command works like a restaurant order slip. The waiter writes down 'make a burger' instead of cooking it themselves. That slip can be handed to the kitchen, held in a queue, or used later to undo the order. In code, a command packages up 'do this action' as an object, so you can store it, pass it around, and even reverse it.

How it works

  1. 1You wrap an action in a command object with an `execute` method that performs it.
  2. 2You can also give it an `undo` method that reverses the action.
  3. 3Instead of calling the action directly, you call `execute()` on the command. The caller never needs to know the details.

When you'd use it

Use this when you want to queue actions, log them, or support undo/redo. Think remote controls, menu actions, or task queues.

Common beginner mistakes

  • Make undo mirror execute exactly, or undo won't actually reverse things.
  • Don't put the action's real logic outside the command. That defeats the point of wrapping it.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Light on
Light off

Not sure this is the right topic? See the learning paths → or where this leads →