☰ All patterns
Command
Turn actions into objects so you can queue, log and undo them.
01
Explain it like I'm new
Real-life analogy
A restaurant order ticket
The waiter writes your order on a ticket. It can be queued, handed to any cook, kept as a record, and torn up if you cancel.
😩 The problem
A text editor needs undo. If edits are just function calls that change text directly, there's no record of what happened or how to reverse it.
💡 The pattern
Wrap each action in an object with Execute() and Undo(). A history stack runs commands and pops them to undo.
02
Play with it
An interactive model of the pattern. Click around, nothing can break.
History stack (top = last command)
- empty
💡 Each button creates a command object. Undo pops the top one and calls its Undo(). DeleteCmd remembered what it deleted!
03
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
04
When should I use it?
✅ Reach for it when…
- •Undo/redo, job queues, macro recording, transactional operations.
🚫 Skip it when…
- •Simple one-off calls with no need to store, delay or reverse them.
🐹 Go tip
For a job queue, send commands over a channel to worker goroutines. Command and worker pool fit together nicely.
🌍 You've already seen it in
exec.Cmd wraps a process to run later. Task queues like asynq and machinery store jobs as command objects.
05
Quick check
One question. No pressure.
Why does DeleteCmd store the `deleted` text?
Related: Strategy, Worker Pool