An action, ready to be packaged.
- Do what?
- —
- To what?
- —
- With what?
- —
Appearance
COMMAND / THE IDEA IN A MINUTE
Command puts an action and the information it needs into one object. Other code can run that request without knowing how the work is done.
Think “append this text to this document.” Keep that request, and an editor can run it, remember it and—with an undo method—reverse it.
SEE IT HAPPEN / FOUR SMALL ACTIONS
Follow one command from creation to redo. You control each step; nothing runs automatically.
Choose an edit. First, we’ll put the request into an object—without changing the document yet.
Hello
Still Hello. Creating a request has no effect on the text.
Put the action, document and text together.
The document says Hello. No command has been created yet.
WHY ADD THIS OBJECT?
Now imagine Append, Replace and Clear, each available from a button, menu or shortcut. They all need to work with the same undo history.
THE PRESSURE / DIRECT HANDLERS
If each handler saves old text and clears redo, every new edit must repeat those rules correctly.
WITH COMMAND / SEPARATE THE JOBS
Add a compatible Clear command and connect a control to it. History still uses the same execute() and undo() methods.
A shared function or snapshot helper may be enough for a small editor. Command becomes useful when requests need their own behavior and data, and you want to pass them between controls, history or other invokers.
THE STRUCTURE / PUT NAMES TO WHAT YOU SAW
In the editor, controls create a command, history invokes it, and the command calls the document. Here are the pattern names for those jobs.
01 / Client
Editor controls
Chooses an edit, supplies the document and text, and gives the command to history.
02 / Invoker
CommandHistory
Calls execute() or undo() through Command. It manages history without knowing how text is edited.
03 / Command
InsertText / ReplaceText
Holds the document and text argument. It performs the edit and saves what its undo needs.
04 / Receiver
TextDocument
Reads and writes the text. It does not know about buttons, shortcuts or undo history.
The shared Command contract is execute() and undo() in this example. Both edit classes implement it. History knows that contract; each command knows its document.
Different controls can create the same kind of command. A history can keep commands for undo; another invoker could schedule or log them. Each capability needs its own rules.
One fixed action may need only a function. Command adds objects, and our saved text uses memory. Some effects, such as sending an email, cannot simply be undone.
See the working before/after code, then experiment with your own edits and history branches.
Three chapters · direct calls, repeated policy, command objectsBACK FOR A REFRESHERRecall the roles, history rules and limits of undo.
TypeScript + Kotlin · contracts and tradeoffs