Command: Undo/Redo & Queued Actions
You'll learn to
- -Explain Command as "turn a request into an object", using a restaurant order slip
- -Build an undo and redo history from execute and undo methods and watch it run
- -Tell Command from Strategy, and see why it suits job queues and macros
In a restaurant, the waiter does not shout your order at the cook. They write it on a slip. The slip can wait on a rail, be passed from person to person, be changed, or be canceled, and it carries everything needed to make the dish. The Command pattern turns a request into an object in the same way. Instead of calling "do this now", you create an object that means "do this", and you can store it, send it, run it later, or reverse it.
The Core Mechanic
A plain method call has no memory. Once document.insert(text) returns, nothing remembers what was inserted. A command object keeps what it needs, such as the exact text, so it can undo itself. The demo uses a tiny text document, with a history that supports both undo and redo. Watch the content after each step.
The Remote-Control and Queue Framing
The other classic picture is a universal remote. Each button is bound to a command object, such as LightOnCommand or TvOnCommand. The remote's press_button() just calls execute() on whatever is bound, and it never needs to know what a light or a TV does.
The same shape powers job queues and macros. You can build a list of command objects, save it, and have a worker run them later in order, even though the worker has no idea what any single command does.
Command and Strategy both wrap behavior behind an interface. Command models a request with a history, undo or queue concern. Strategy models a swappable algorithm that has no notion of "undo" or "when it ran".
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!