Command Pattern
Represent a request as an object so creating it and executing it can happen at different times.
· Last updated: 2026-11-07 · 9 min read
Overview
Pressing a button may queue an edit instead of applying it immediately, and the queued work then runs in order. In that case the queue must retain not just the method name but also which value goes to which target. Call the method on the spot and the edit is over. Nothing is left to put in the queue.
Put target and argument in one object: the queue handles order, the caller picks the moment. Command turns a request into an object. The receiver does the work; the invoker calls Execute(). Here a text buffer and a command queue hold those roles.
UML
CommandQueue stores only ICommand objects. AppendText keeps a TextBuffer and the string to append as fields, and calls the buffer's Append() when Execute() runs. The buffer does the edit; the command holds the target and argument.
History
GoF cataloged Command as a behavioral pattern in Design Patterns in 1994. Object requests can be managed in structures such as queues and execution histories.1
Reifying a user action into a first-class object that supports menu binding, scripting, and multi-level Undo/Redo was pioneered in late-1980s GUI frameworks—most notably Apple's MacApp, ET++, and the Unidraw graphical editor framework designed by John Vlissides and Mark Linton.2
Why use it?
A queue can manage execution order without knowing each edit. New kinds of edits leave its job unchanged. Callers can also create a request now and execute it later.
A command object does not bring undo or duplicate prevention with it. The pattern covers the step that turns a request into an object, and stops there. Undo needs saved state or an inverse operation; commands with external effects also need an explicit re-execution policy.
Example
Build one append command and execute it. The split shows up here.
using System;
using System.Collections.Generic;
using System.Linq;
var buffer = new TextBuffer();
ICommand command = new AppendText(buffer, "A");
command.Execute();
Console.WriteLine(buffer.Text);
sealed class TextBuffer
{
public string Text { get; private set; } = "";
public void Append(string value) => Text += value;
}
interface ICommand { void Execute(); }
// Retain the receiver and arguments in the command for later execution.
sealed class AppendText(TextBuffer buffer, string value) : ICommand
{
public void Execute() => buffer.Append(value);
}
// The queue manages order through execute without knowing the details of an edit.
sealed class CommandQueue
{
private readonly Queue<ICommand> commands = new();
public void Add(ICommand command) => commands.Enqueue(command);
public void RunAll()
{
while (commands.TryDequeue(out var command)) command.Execute();
}
}
AAppendText retains both the buffer and the string it will append.
An extended example
Queue two commands. The buffer stays empty until RunAll() runs them in order. Creating and running are two steps.
using System;
using System.Collections.Generic;
using System.Linq;
var buffer = new TextBuffer();
var queue = new CommandQueue();
queue.Add(new AppendText(buffer, "A"));
queue.Add(new AppendText(buffer, "B"));
Console.WriteLine("before: [" + buffer.Text + "]");
queue.RunAll();
Console.WriteLine("after: [" + buffer.Text + "]");
sealed class TextBuffer
{
public string Text { get; private set; } = "";
public void Append(string value) => Text += value;
}
interface ICommand { void Execute(); }
// Retain the receiver and arguments in the command for later execution.
sealed class AppendText(TextBuffer buffer, string value) : ICommand
{
public void Execute() => buffer.Append(value);
}
// The queue manages order through execute without knowing the details of an edit.
sealed class CommandQueue
{
private readonly Queue<ICommand> commands = new();
public void Add(ICommand command) => commands.Enqueue(command);
public void RunAll()
{
while (commands.TryDequeue(out var command)) command.Execute();
}
}
before: []
after: [AB]This is a synchronous in-memory queue, without persistence, crash recovery or resume-after-failure behavior. Executing the same AppendText again appends its text again.
TypeScript example
The buffer performs edits, AppendText retains a target and arguments, and the queue controls execution order. So a request can be created before the edit runs. Bundle all three roles into one class and the execution moment has nowhere to move.
class TextBuffer {
#text = "";
get text(): string { return this.#text; }
append(value: string): void { this.#text += value; }
}
interface ICommand { execute(): void; }
// Retain the receiver and arguments in the command for later execution.
class AppendText implements ICommand {
constructor(private readonly buffer: TextBuffer, private readonly value: string) {}
execute(): void { this.buffer.append(this.value); }
}
// The queue manages order through execute without knowing the details of an edit.
class CommandQueue {
private readonly commands: ICommand[] = [];
add(command: ICommand): void { this.commands.push(command); }
runAll(): void {
for (;;) {
const command = this.commands.shift();
if (command === undefined) return;
command.execute();
}
}
}
const buffer = new TextBuffer();
const queue = new CommandQueue();
queue.add(new AppendText(buffer, "A"));
queue.add(new AppendText(buffer, "B"));
console.log("before: " + buffer.text);
queue.runAll();
console.log("after: " + buffer.text);before:
after: ABEnqueueing does not edit the buffer. This synchronous in-memory queue supplies no undo, recovery after failure, or duplicate-execution prevention.
Connecting commands to receivers with Command<TReceiver>
A command stores what to do, while its receiver is the object that work changes. With the roles split, you can choose which side's type the command is bound to. ICommand<TReceiver> declares the receiver type, so the type checker rejects sending an AddCommand for a Counter to an unrelated object.
Creating AddCommand does not change the counter. Passing the command and its receiver to Invoker.ExecuteCommand() calls ExecuteCommand(), and only then does the receiver's value change. That leaves room between building a command and running it. Invoker and Command keep their role names so the pattern stays visible in the code.
C#
using System;
var counter = new Counter();
ICommand<Counter> command = new AddCommand(5);
Console.WriteLine(counter.Value);
new Invoker<Counter>().ExecuteCommand(command, counter);
Console.WriteLine(counter.Value);
// TYPES
interface ICommand<TReceiver> { void ExecuteCommand(TReceiver receiver); }
sealed class Invoker<TReceiver>
{
public void ExecuteCommand(ICommand<TReceiver> command, TReceiver receiver)
=> command.ExecuteCommand(receiver);
}
sealed class Counter
{
public int Value { get; private set; }
public void Add(int value) { Value += value; }
}
sealed class AddCommand : ICommand<Counter>
{
private readonly int amount;
public AddCommand(int amount) { this.amount = amount; }
// Store the amount and delegate to the receiver supplied at execution.
public void ExecuteCommand(Counter receiver) => receiver.Add(amount);
}0
5TypeScript
interface Command<TReceiver> { executeCommand(receiver: TReceiver): void; }
class Invoker<TReceiver> {
executeCommand(command: Command<TReceiver>, receiver: TReceiver): void {
command.executeCommand(receiver);
}
}
class Counter {
#value = 0;
get value(): number { return this.#value; }
add(value: number): void { this.#value += value; }
}
class AddCommand implements Command<Counter> {
constructor(private readonly amount: number) {}
// Apply the stored request to the receiver at execution time.
executeCommand(receiver: Counter): void { receiver.add(this.amount); }
}
const counter = new Counter();
const command: Command<Counter> = new AddCommand(5);
console.log(counter.value);
new Invoker<Counter>().executeCommand(command, counter);
console.log(counter.value);0
5This command adds to the value every time it executes. Separating when a command runs and preventing a double run are different requirements; retries or network delivery need their own duplicate-handling rule. Hand the same command over twice and the value changes twice.
The official references describe the type-parameter syntax and library contracts.3
Boundary with first-class closures, Undo, and compensating actions
Because modern languages have first-class closures—such as C#'s Action delegates and TypeScript's arrow functions (() => buffer.append("a"))—a closure that captures its receiver and arguments is already a lightweight command. If all you need is to defer or enqueue a single callback, defining a dedicated ICommand class is unnecessary boilerplate. Explicit command objects earn their keep when a request needs multiple lifecycle operations or inspectable metadata: pairing Execute() with Undo(), coalescing adjacent edits in an undo stack, or serializing commands to an audit log or durable queue.
When adding Undo(), separate in-memory state reversal from irreversible external side effects. Truncating a text buffer or restoring a Memento Pattern snapshot cleanly reverses local memory, whereas an email already sent or a credit card already charged cannot be "un-called" by rolling back a field. Commands that cross process boundaries require explicit compensating actions (such as issuing a refund transaction) and Idempotency keys so retries after a crash do not apply the same mutation twice.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Behavioral patterns, Command. ↩
- John M. Vlissides and Mark A. Linton, "Unidraw: A Framework for Building Domain-Specific Graphical Editors," ACM Transactions on Information Systems 8(3), 1990, pp. 237–268. DOI. ↩
- C# generics; TypeScript generics ↩