Behavioral

Command

Encapsulates a request as an object.

Undo/redo operationsTask queuesMacro recording

Understanding Command

The Command pattern encapsulates a request as an object, allowing you to parameterize clients with different requests, queue them, log them, and support undo operations. Each command object contains all the information needed to execute the action — the receiver, the method to call, and any arguments. In Go, a command is typically a struct implementing an Execute() interface, with the receiver stored as a field. This decouples the invoker (what triggers the action) from the receiver (what performs it), enabling powerful patterns like undo/redo stacks.

Key Concepts

  • Command interface — defines Execute() (and optionally Undo()) that all commands must implement
  • Concrete commands — structs that hold a receiver reference and implement the action-specific logic
  • Invoker — triggers commands without knowing what they do — just calls Execute()
  • Receiver — the object that actually performs the work when the command is executed

When to Use

✅ Use when
  • • You need undo/redo functionality in your application
  • • You want to queue, schedule, or log operations for later execution
  • • You need to parameterize objects with actions (callbacks as objects)
  • • You\'re building a macro or batch execution system
⚠️ Avoid when
  • • Simple function callbacks or closures would suffice in Go
  • • The overhead of command objects isn\'t justified by the flexibility gained
  • • There\'s no need for undo, queuing, or logging of operations

Structure

Invoker
↓ calls Execute()
<<Command>> Execute()
↓ delegates to
Receiver

How It Works

LightOn
LightOff
Commands
Command Queue
Cmd
Cmd
...
💡 Light
OFF
Actions as objects
1

Action as Object

Encapsulate a request as an object.

1 / 4

Basic Implementation

Remote control with undo functionality:

main.go
Loading editor...

Real-World Example: Text Editor

Text operations as commands with macro support:

main.go
Loading editor...