Skip to main content
Design Patterns 80 XP · 8 min

Command: Encapsulating Requests

Transform a request into a standalone object — enabling undo/redo, queuing, logging, and deferred execution of operations.

Showing
Ad (728×90)

Why this matters

When you call a method directly, the action evaporates — there is no record, no way to reverse it, no way to defer or queue it. The Command pattern turns each operation into an object with execute() and undo(). A history stack of Command objects gives you Ctrl+Z for free. The same approach enables scheduled tasks, job queues, audit logs, and transaction rollbacks.

The problem

Bad

The solution

Good

Beyond undo/redo

Command objects can be serialized and stored — enabling deferred execution (run this at midnight), distributed task queues (Celery, Bull), and event sourcing (the entire history of changes is a list of commands that can be replayed). Every git commit is a Command. Every database migration is a Command. The pattern is ubiquitous once you see it.

Key takeaway

Whenever you need undo/redo or operation history, Command turns actions into objects that can be stored, replayed, and reversed — the history stack does the rest.

Done with this lesson?

Mark it complete to earn XP and track your progress.