Facebook Pixel

Command Pattern

Encapsulating a request as an object

A text editor has a toolbar. Clicking the Bold button calls editor.toggle_bold() directly. A keyboard shortcut also triggers bold — so it calls editor.toggle_bold() again. A macro recorder needs to capture the action. An undo stack needs to reverse it. Now the toolbar button, the keyboard handler, the macro recorder, and the undo system are all tangled around the same direct call, and adding any new trigger means touching all of them.

The naive approach makes every caller responsible for knowing exactly what to call and how to reverse it:

1# Bad: the toolbar button knows about the editor's internals and
2# has no standard way to support undo or macro replay.
3class ToolbarButton:
4    def __init__(self, editor: "Editor", action: str) -> None:
5        self._editor = editor
6        self._action = action
7
8    def click(self) -> None:
9        if self._action == "bold":
10            self._editor.toggle_bold()
11        elif self._action == "italic":
12            self._editor.toggle_italic()
13        elif self._action == "save":
14            self._editor.save_to_disk()
15        # Every new action adds a branch here.

How it works

The Command pattern gives each action its own class. That class — the command — captures everything needed to perform the action: a reference to the receiver (the editor), the method to call, and any parameters. The invoker (the toolbar button, the keyboard handler) holds a reference to a command object and calls execute(). It never reaches through to the receiver.


The invoker calls command.execute() without knowing which command is installed. To swap actions at runtime — a keyboard shortcut that remaps during a modal dialog, for instance — you replace the command object. The invoker's code does not change.

Because each command is an object, you can collect them. An undo stack is a list of executed commands; calling undo() in reverse order reverses each action. A macro is a list of commands executed in sequence. A job queue is a list of commands dispatched to worker threads.

Good: one class per action, a shared interface

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro