Design Patterns

Pattern 14 of 23, Behavioral family

Command

Also known as: Action

Turn a request into a standalone object: it can then be passed as a parameter, queued, logged or undone.

The problem

An editor has buttons, shortcuts and menus that trigger the same actions. It also needs undo/redo. Putting the logic in each button duplicates code and makes undo impossible.

The solution

Encapsulate each action in a Command object with execute() and undo(). An invoker (history) executes the commands and pushes them onto a stack.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The click creates a command object that carries its receiver.
  2. The invoker receives the command without knowing what it does.
  3. History [ ] โ†’ WriteCommand: execute()
  4. The command acts on the receiver.
  5. The command is pushed onto the history.
  6. The user undoes.
  7. History [WriteCommand] โ†’ WriteCommand: pop().undo()
  8. The previous state is restored.

An analogy

At a restaurant, the waiter writes your order on a ticket: the ticket can be queued, handed to the chef, or cancelled.

When to use it

  • Undo / redo, action history
  • Job queues, deferred tasks
  • Macros, transactions, CQRS

Pros and cons

Pros

  • Decouples the sender from the executor
  • Easy undo/redo and logging
  • Command composition (macros)

Cons

  • Lots of small classes
  • Undo gets complex when state is not easily reversible

Implementations

The same example, written idiomatically in each language.

Command in Python

command.py 44 lines
from abc import ABC, abstractmethod


class Editor:
    def __init__(self):
        self.text = ""


class Command(ABC):
    @abstractmethod
    def execute(self) -> None: ...
    @abstractmethod
    def undo(self) -> None: ...


class Write(Command):
    def __init__(self, editor: Editor, s: str):
        self.editor, self.s = editor, s

    def execute(self):
        self.editor.text += self.s

    def undo(self):
        self.editor.text = self.editor.text[: -len(self.s)]


class History:
    def __init__(self):
        self._stack: list[Command] = []

    def run(self, cmd: Command):
        cmd.execute()
        self._stack.append(cmd)

    def undo(self):
        if self._stack:
            self._stack.pop().undo()


ed, h = Editor(), History()
h.run(Write(ed, "Hello "))
h.run(Write(ed, "World"))
h.undo()
print(ed.text)   # "Hello "

Command in TypeScript

command.ts 24 lines
interface Command {
  execute(): void;
  undo(): void;
}

class Editor { text = ""; }

class WriteCommand implements Command {
  constructor(private editor: Editor, private s: string) {}
  execute() { this.editor.text += this.s; }
  undo() { this.editor.text = this.editor.text.slice(0, -this.s.length); }
}

class History {
  private stack: Command[] = [];
  run(c: Command) { c.execute(); this.stack.push(c); }
  undo() { this.stack.pop()?.undo(); }
}

const ed = new Editor();
const h = new History();
h.run(new WriteCommand(ed, "Hello "));
h.run(new WriteCommand(ed, "World"));
h.undo(); // ed.text === "Hello "

Command in Java

command.java 19 lines
interface Command {
    void execute();
    void undo();
}

class Editor { final StringBuilder text = new StringBuilder(); }

record WriteCommand(Editor editor, String s) implements Command {
    public void execute() { editor.text.append(s); }
    public void undo() { editor.text.setLength(editor.text.length() - s.length()); }
}

class History {
    private final Deque<Command> stack = new ArrayDeque<>();

    void run(Command c) { c.execute(); stack.push(c); }

    void undo() { if (!stack.isEmpty()) stack.pop().undo(); }
}

Command in C#

command.cs 22 lines
interface ICommand
{
    void Execute();
    void Undo();
}

class Editor { public string Text { get; set; } = ""; }

class WriteCommand(Editor editor, string s) : ICommand
{
    public void Execute() => editor.Text += s;
    public void Undo() => editor.Text = editor.Text[..^s.Length];
}

class History
{
    private readonly Stack<ICommand> _stack = new();

    public void Run(ICommand c) { c.Execute(); _stack.Push(c); }

    public void Undo() { if (_stack.TryPop(out var c)) c.Undo(); }
}

Command in PHP

command.php 30 lines
interface Command
{
    public function execute(): void;
    public function undo(): void;
}

final class Editor { public string $text = ''; }

final class WriteCommand implements Command
{
    public function __construct(private Editor $editor, private string $s) {}

    public function execute(): void { $this->editor->text .= $this->s; }

    public function undo(): void
    {
        $this->editor->text = substr($this->editor->text, 0, -strlen($this->s));
    }
}

final class History
{
    private array $stack = [];

    public function run(Command $c): void { $c->execute(); $this->stack[] = $c; }

    public function undo(): void { array_pop($this->stack)?->undo(); }
}

// Laravel Jobs (dispatch(new SendInvoice($order))) are queued commands

Command in Go

command.go 28 lines
type Command interface {
    Execute()
    Undo()
}

type Editor struct{ Text string }

type WriteCommand struct {
    ed *Editor
    s  string
}

func (c WriteCommand) Execute() { c.ed.Text += c.s }
func (c WriteCommand) Undo()    { c.ed.Text = c.ed.Text[:len(c.ed.Text)-len(c.s)] }

type History struct{ stack []Command }

func (h *History) Run(c Command) {
    c.Execute()
    h.stack = append(h.stack, c)
}

func (h *History) Undo() {
    if n := len(h.stack); n > 0 {
        h.stack[n-1].Undo()
        h.stack = h.stack[:n-1]
    }
}

Frequently asked questions

What is the Command design pattern?

Turn a request into a standalone object: it can then be passed as a parameter, queued, logged or undone. Encapsulate each action in a Command object with execute() and undo(). An invoker (history) executes the commands and pushes them onto a stack.

When should you use the Command pattern?

Undo / redo, action history; Job queues, deferred tasks; Macros, transactions, CQRS.

What are the pros and cons of the Command pattern?

Pros: Decouples the sender from the executor; Easy undo/redo and logging; Command composition (macros). Cons: Lots of small classes; Undo gets complex when state is not easily reversible.