Command
A command is an object that stands for a request: receiver plus action plus arguments. You queue it, log it, undo it, or run it later without the caller knowing the receiver.
Detailed Explanation
A menu item should not call document.bold() directly if you also need undo, macros, and a button that does the same thing. A BoldCommand stores the document and the previous style. execute applies bold. undo restores. The menu and the button both run the command. A queue of commands is a macro.
Runnable and Callable are commands with a small API. ExecutorService runs commands. A record Undoable(Runnable apply, Runnable undo) is a tiny command. GUI toolkits used this everywhere.
Command vs strategy: a strategy is "how to do this kind of work" and is usually stateless policy. A command is "this particular request" and often holds arguments and undo state. Command vs observer: observer broadcasts an event; command is a first-class request you can store.
You reach for command when you need undo, scheduling, or a log of actions. You keep a direct method call when none of that exists. You do not wrap every call in a command class; a lambda on an executor is enough for "run later".
The cost of a command per click is many small classes. Use records and lambdas. The cost of undo that shares mutable state with execute is an undo that does not undo. Store snapshots or inverse operations. The cost of a command that holds a huge document by identity is a leak if the queue is long.
Serialization of commands is how some systems persist a work queue. Then the command becomes a public API; version it.
Code Examples
import java.util.ArrayDeque;
import java.util.Deque;
interface Command {
void execute();
void undo();
}
class Editor {
String text = "";
}
class TypeCmd implements Command {
private final Editor editor;
private final String chunk;
TypeCmd(Editor editor, String chunk) {
this.editor = editor;
this.chunk = chunk;
}
@Override
public void execute() {
editor.text += chunk;
}
@Override
public void undo() {
editor.text = editor.text.substring(0, editor.text.length() - chunk.length());
}
}
public class UndoStack {
public static void main(String[] args) {
Editor ed = new Editor();
Deque<Command> undo = new ArrayDeque<>();
Command c = new TypeCmd(ed, "Hi");
c.execute();
undo.push(c);
undo.pop().undo();
System.out.println("[" + ed.text + "]"); // prints: []
}
}Common Gotchas
A long command queue retains receivers
bound it or store ids.