Command pattern
suggest changeThe command pattern packages an operation and its arguments as an object. A command can then be queued, logged, retried, or executed later without the invoker knowing the receiver's implementation.
The pattern has three participants:
- The command exposes an operation such as
execute(). - The invoker decides when to execute a command.
- The receiver performs the underlying work.
class DocumentEditor {
#text = '';
append(text) {
this.#text += text;
}
get text() {
return this.#text;
}
}
class AppendTextCommand {
constructor(editor, text) {
this.editor = editor;
this.text = text;
}
execute() {
this.editor.append(this.text);
}
}
class CommandQueue {
#commands = [];
enqueue(command) {
this.#commands.push(command);
}
run() {
for (const command of this.#commands) {
command.execute();
}
this.#commands.length = 0;
}
}
const editor = new DocumentEditor();
const queue = new CommandQueue();
queue.enqueue(new AppendTextCommand(editor, 'Hello'));
queue.enqueue(new AppendTextCommand(editor, ' world'));
queue.run();
console.log(editor.text); // 'Hello world'
For simple one-off operations, storing functions may be sufficient. Dedicated command objects become valuable when commands need metadata, validation, serialization, undo behavior, or a shared interface.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents