Command Pattern
Most of the time, calling a method is all you need: doc.insert(0, "Hi") runs now and is forgotten. But some
designs need more from an action than running it. A text editor must undo it. A job scheduler must run it later.
A smart home hub must queue it, retry it and show it in a history. You can't do any of that with a method call
that has already happened.
The Command pattern turns each action into an object. The object knows how to run itself and, if needed, how to undo itself. Once actions are objects, you can put them in a stack, a queue or a log like any other value.
🎮 In one sentence: wrap each request in an object with an
execute()method (and oftenundo()), so requests can be stored, queued, undone, redone and logged instead of just run.
The Problem It Solves
Here is a tiny text editor whose buttons call the document directly. Then someone asks for undo, and the first attempt records what happened as tuples:
class Editor:
def __init__(self) -> None:
self.text = ""
self.history: list[tuple] = []
def insert(self, pos: int, s: str) -> None:
self.text = self.text[:pos] + s + self.text[pos:]
self.history.append(("insert", pos, s))
def delete(self, pos: int, length: int) -> None:
removed = self.text[pos:pos + length]
self.text = self.text[:pos] + self.text[pos + length:]
self.history.append(("delete", pos, removed))
def undo(self) -> None:
if not self.history:
return
kind, pos, s = self.history.pop()
if kind == "insert":
self.text = self.text[:pos] + self.text[pos + len(s):]
elif kind == "delete":
self.text = self.text[:pos] + s + self.text[pos:]
It works for two actions. Then the feature list grows.
Every action is written twice, far apart. The "do" half lives in insert; the "undo" half lives in a branch
of undo. Adding "replace" or "uppercase selection" means editing both places and keeping the tuple layout in
sync by hand. Forget the branch and undo silently does nothing.
Redo needs a third copy. Redo has to re-apply an action, so it needs its own if kind == ... chain, which
repeats the logic in insert and delete.
The tuples mean nothing on their own. ("delete", 4, "lo") stores the removed text in the slot where
insert stores the inserted text. Nothing checks that, and a typo like "delte" is ignored.
Nothing else can use the actions. A macro ("record these steps and replay them"), a keyboard shortcut and a
toolbar button all want to trigger the same actions, but the actions only exist as methods on Editor.
⚠️ The smell to look for: a history list of tuples or strings with a
switchon the action name inundo, or a request to "run this later", "retry this" or "replay these". That is the cue for Command.