Command pattern

suggest change

The 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:

  1. The command exposes an operation such as execute().
  2. The invoker decides when to execute a command.
  3. 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents