Codacoda
Back to Academy

design patterns

Command

The Command pattern encapsulates a request as an object, thereby allowing you to parameterize clients with different requests, queue or log requests, and support undoable operations. The key participants are the Command (declares an interface for executing an operation), ConcreteCommand (binds a receiver to an action), Receiver (knows how to perform the operations), Invoker (asks the command to carry out the request), and Client (creates a ConcreteCommand and sets its receiver). Think of ordering at a restaurant: your order (command) is written on a ticket that the waiter (invoker) passes to the kitchen (receiver) — the ticket can be queued, logged, or cancelled. Use Command when you want to parameterize objects with an action, specify, queue, and execute requests at different times, or support undo.

Use Cases

  • Undo/redo functionality in text editors
  • Task queuing and deferred execution
  • Macro recording and playback
  • Transactional operations with rollback support

Visualization

callsInvoker+setCommand()+executeCommand()<<interface>>Command+execute()+undo()ConcreteCommand+execute()+undo()-receiverReceiver+action()
Speed:1x
Command — encapsulates a request as an object, enabling parameterization and undoStep 1 / 7

Implementation

Output

Click "Run Code" to see output...