Design Patterns III — Behavioral
What you’ll learn. Nine behavioral patterns that govern how objects interact and divide work: Strategy, Observer, Command, State, Template Method, Iterator, Chain of Responsibility, Visitor and Mediator. Many collapse to first-class functions in Python/TypeScript; knowing both the classical form and the modern idiom is the goal. Code is labelled Python or TypeScript.
Strategy
Section titled “Strategy”Problem. An algorithm has several interchangeable variants (sorting, pricing, compression, routing), and hard-coding with if/else makes the host class bloated and closed to extension.
Idea. Encapsulate each algorithm behind a common interface and let the client pick one. It is composition-over-inheritance in its purest form (Core Principles).
# Python: in a language with first-class functions, a strategy is a callablefrom typing import Callable
Pricing = Callable[[float], float]
def regular(total: float) -> float: return totaldef black_friday(total: float) -> float: return total * 0.7def loyalty(total: float) -> float: return total - min(total * 0.1, 20)
class Checkout: def __init__(self, pricing: Pricing = regular): self.pricing = pricing def total(self, items: list[float]) -> float: return self.pricing(sum(items))
Checkout(black_friday).total([10, 20]) # 21.0Use classes when a strategy has its own configuration or state; use functions otherwise. sorted(xs, key=...) and Array.prototype.sort(cmp) are Strategy. Pitfall: clients must understand the differences to choose; too many fine-grained strategies is combinatorial configuration.
Observer
Section titled “Observer”Problem. One object’s state change must notify others, but the subject should not know who they are (loose coupling). Think UI events, model-view, pub/sub.
Idea. The subject keeps a list of subscribers and notifies them on change.
// TypeScript: typed event emittertype Listener<T> = (event: T) => void;
class EventEmitter<T> { private listeners = new Set<Listener<T>>(); subscribe(l: Listener<T>): () => void { // returns an unsubscribe function this.listeners.add(l); return () => this.listeners.delete(l); } emit(e: T) { for (const l of [...this.listeners]) l(e); } // copy: safe against mutation}
const priceChanged = new EventEmitter<{ symbol: string; price: number }>();const off = priceChanged.subscribe(e => console.log(e.symbol, e.price));priceChanged.emit({ symbol: "ABC", price: 12.3 });off();Observer is the core of GUI frameworks, DOM addEventListener, reactive programming (RxJS, signals in Angular/Solid/Vue), and, scaled across processes, message brokers (System Design Fundamentals on queues, Architecture Styles on event-driven design).
Pitfalls: memory leaks (the “lapsed listener”: forgotten unsubscribes keep objects alive; use weak references or return unsubscribe handles); unpredictable order and cascading updates (A’s handler triggers B’s, which triggers A); exceptions in one handler breaking others; re-entrancy; and synchronous notification blocking the emitter. In-process Observer is synchronous and ordered by default; distributed pub/sub is asynchronous and loses these guarantees.
Command
Section titled “Command”Problem. You want to treat a request as an object: queue it, log it, undo it, retry it, or send it over a wire.
Idea. Encapsulate an action and its parameters in an object with an execute() (and optionally undo()) method.
# Python: undoable text editor commandsclass Editor: def __init__(self): self.text = ""
class Insert: def __init__(self, ed: Editor, s: str): self.ed, self.s = ed, s def execute(self): self.ed.text += self.s def undo(self): self.ed.text = self.ed.text[: -len(self.s)]
class History: def __init__(self): self.done: list = [] def run(self, cmd): cmd.execute(); self.done.append(cmd) def undo(self): if self.done: self.done.pop().undo()
ed, h = Editor(), History()h.run(Insert(ed, "Hello ")); h.run(Insert(ed, "World"))h.undo()assert ed.text == "Hello "Uses: undo/redo, macro recording, job queues and task schedulers (Celery tasks are serialized commands), transactional operations, and CQRS commands (Architecture Styles). Event sourcing stores state-change records as the source of truth. A serialized command with an idempotency key is also the basis of reliable retries (Distributed Systems). Undo is hard: you must store enough state (memento) to reverse the action, and external side effects (sent emails) cannot be undone, only compensated.
Problem. An object’s behavior depends on its state, leading to huge switch statements on a status field replicated across methods.
Idea. Model each state as an object (or a transition table); the context delegates to the current state, which handles the event and chooses the next state.
// TypeScript: order lifecycle as a discriminated union + transition functiontype Order = | { status: "pending" } | { status: "paid"; paidAt: Date } | { status: "shipped"; trackingId: string } | { status: "cancelled"; reason: string };
type Event = | { type: "pay"; at: Date } | { type: "ship"; trackingId: string } | { type: "cancel"; reason: string };
function transition(o: Order, e: Event): Order { switch (o.status) { case "pending": if (e.type === "pay") return { status: "paid", paidAt: e.at }; if (e.type === "cancel") return { status: "cancelled", reason: e.reason }; break; case "paid": if (e.type === "ship") return { status: "shipped", trackingId: e.trackingId }; if (e.type === "cancel") return { status: "cancelled", reason: e.reason }; break; } throw new Error(`Illegal transition ${o.status} -> ${e.type}`);}The classical GoF form uses polymorphic state classes; the modern functional form (above) is a finite state machine as a pure function, easier to test and to model-check. Draw the state diagram first; each (state, event) pair is either a defined transition or explicitly illegal. State machines appear in protocol implementations (TCP), workflows, UI flows, and game AI. Libraries such as XState (TypeScript) and transitions (Python) formalize them. Pitfall: boolean-flag soup (isPaid, isShipped, isCancelled) allows impossible combinations; make illegal states unrepresentable.
Template Method
Section titled “Template Method”Problem. Several algorithms share the same skeleton but differ in some steps.
Idea. A base class defines the algorithm’s fixed sequence and calls abstract “hook” methods that subclasses fill in (the “Hollywood principle”: don’t call us, we’ll call you).
from abc import ABC, abstractmethod
class ReportJob(ABC): def run(self) -> None: # the template: not overridden data = self.extract() rows = self.transform(data) self.load(rows) self.notify() @abstractmethod def extract(self): ... @abstractmethod def transform(self, data): ... def load(self, rows): print(f"loading {len(rows)} rows") def notify(self): pass # optional hookIt is inheritance-based, so it carries inheritance’s rigidity; frameworks use it extensively (unittest’s setUp/tearDown, servlets, Django class-based views). The composition-based alternative is Strategy: pass the varying steps as functions or objects (run_job(extract, transform, load)). Prefer Strategy unless the framework dictates the template or the number of steps is large and stable.
Iterator
Section titled “Iterator”Problem. Traverse a collection without exposing its internal representation, and allow multiple traversal types.
Idea. An object that yields successive elements. This pattern is now built into virtually every language (__iter__/__next__ in Python, Symbol.iterator in JS/TS, Iterator in Rust/Java). Generators make custom iterators trivial and lazy.
# Python: lazy tree traversal with a generatordef inorder(node): if node: yield from inorder(node.left) yield node.value yield from inorder(node.right)
# Lazy pipeline: only as much work as consumedfrom itertools import islicefirst_five_evens = list(islice((x for x in inorder(root) if x % 2 == 0), 5))// TypeScript: async iterators model paginated APIs elegantlyasync function* allUsers(fetchPage: (c?: string) => Promise<{ items: User[]; next?: string }>) { let cursor: string | undefined; do { const page = await fetchPage(cursor); yield* page.items; cursor = page.next; } while (cursor);}for await (const u of allUsers(api.listUsers)) { /* ... */ }Key benefits: laziness (memory use is O(1) for streams), uniformity, and decoupling of algorithms from containers. Pitfalls: modifying a collection while iterating (undefined behavior or exceptions); one-shot iterators that cannot be replayed; leaking resources if iteration stops early (use try/finally or context managers).
Chain of Responsibility
Section titled “Chain of Responsibility”Problem. A request must be handled by one of several handlers (or processed by several in sequence), and the sender should not know which.
Idea. Link handlers in a chain; each decides to handle the request, modify it, or pass it on.
# Python: authorization / validation pipelineclass Handler: def __init__(self, nxt=None): self.nxt = nxt def handle(self, req: dict): if self.nxt: return self.nxt.handle(req) return "OK"
class Authn(Handler): def handle(self, req): if "user" not in req: return "401" return super().handle(req)
class RateLimit(Handler): def handle(self, req): if req.get("count", 0) > 100: return "429" return super().handle(req)
chain = Authn(RateLimit())assert chain.handle({"user": "a", "count": 5}) == "OK"Real instances: HTTP middleware stacks, servlet filters, event bubbling in the DOM, logging levels, exception handling (catch blocks), support escalation tiers. It overlaps with Decorator (each layer wraps the next) but the intent differs: in a chain a link may terminate processing. Pitfalls: a request may go unhandled silently (always define the terminal behavior); long chains hamper debugging; ordering dependencies are implicit.
Visitor
Section titled “Visitor”Problem. You have a stable set of element types (e.g. AST node types) and want to add many new operations (pretty print, type check, evaluate, optimize) without editing each class.
Idea. Define operations in a separate visitor object; elements accept(visitor) and call back the method for their own type (double dispatch).
# Python: expression tree with a visitorfrom dataclasses import dataclass
@dataclassclass Num: value: float
@dataclassclass Add: left: object; right: object@dataclassclass Mul: left: object; right: object
class Evaluator: def visit(self, n): return getattr(self, f"visit_{type(n).__name__}")(n) def visit_Num(self, n): return n.value def visit_Add(self, n): return self.visit(n.left) + self.visit(n.right) def visit_Mul(self, n): return self.visit(n.left) * self.visit(n.right)
class Printer: def visit(self, n): return getattr(self, f"visit_{type(n).__name__}")(n) def visit_Num(self, n): return str(n.value) def visit_Add(self, n): return f"({self.visit(n.left)} + {self.visit(n.right)})" def visit_Mul(self, n): return f"({self.visit(n.left)} * {self.visit(n.right)})"
tree = Add(Num(2), Mul(Num(3), Num(4)))Evaluator().visit(tree) # 14Printer().visit(tree) # (2.0 + (3.0 * 4.0)) (floats print as 2.0)Modern languages with pattern matching and algebraic data types make Visitor largely unnecessary:
// TypeScript: discriminated union + exhaustive switchtype Expr = | { k: "num"; v: number } | { k: "add"; l: Expr; r: Expr } | { k: "mul"; l: Expr; r: Expr };
function evaluate(e: Expr): number { switch (e.k) { case "num": return e.v; case "add": return evaluate(e.l) + evaluate(e.r); case "mul": return evaluate(e.l) * evaluate(e.r); } // compiler checks exhaustiveness (with `never` guard or noImplicitReturns)}This is the other side of the expression problem introduced in Core Principles: Visitor/ADTs make adding operations easy and adding types hard (every visitor changes); polymorphic methods do the opposite. Choose the axis that is more stable. Compilers, linters, serializers and code generators are the classic Visitor domain. Pitfalls: verbose boilerplate, breaks encapsulation (visitors need access to element internals), hard to follow double dispatch.
Mediator
Section titled “Mediator”Problem. Many objects interact in tangled many-to-many ways, creating tight coupling and a web of references.
Idea. Introduce a central object that coordinates communication; participants only know the mediator.
Without: With Mediator: A <-> B A -\ A <-> C B --> [Mediator] --> routes/coordinates B <-> C (N*(N-1)/2 links) C -/ (N links)// TypeScript: a chat room as a mediatorclass ChatRoom { private users = new Map<string, (from: string, msg: string) => void>(); join(name: string, onMessage: (from: string, msg: string) => void) { this.users.set(name, onMessage); } send(from: string, msg: string) { for (const [name, cb] of this.users) if (name !== from) cb(from, msg); }}Instances: UI dialogs coordinating widgets, air-traffic control, message brokers and event buses, Redux-style stores, application services orchestrating domain objects. Mediator vs Observer. Observer is one-to-many broadcast with the subject unaware of consumers; Mediator is a many-to-many coordinator that knows participants and encodes interaction logic. The main risk is the mediator becoming a god object that holds all the logic; keep it to coordination.
Patterns together and honest perspective
Section titled “Patterns together and honest perspective”Patterns often combine: a Command queue consumed by a Chain of Responsibility pipeline, Strategy for policy inside each handler, State governing the lifecycle, Observer announcing completion. Frameworks embody several at once.
Many of these patterns are modest in modern languages: Strategy and Command are often just lambdas; Iterator is a language feature; Visitor is a match; Observer is a library. The value of the catalog is the vocabulary and trade-off knowledge, not the class diagrams. When a codebase’s pattern count exceeds its problem count, simplify (Core Principles: KISS/YAGNI).
Key takeaways
Section titled “Key takeaways”- Strategy: swap algorithms behind an interface; in modern code, pass a function.
- Observer: decouple publishers from subscribers; watch for leaks, ordering and re-entrancy.
- Command: reify requests for queuing, logging, undo and retry.
- State: model lifecycles as explicit state machines; forbid illegal transitions.
- Template Method: inheritance-based skeleton; Strategy is the composition-based alternative.
- Iterator: lazy, uniform traversal; generators make it trivial.
- Chain of Responsibility: pipeline of handlers that can pass or terminate (middleware).
- Visitor: add operations to a stable type hierarchy; ADTs plus pattern matching often replace it.
- Mediator: centralize many-to-many coordination; do not let it become a god object.
Exercises
Section titled “Exercises”- Conceptual. Contrast Observer and Mediator. Which would you use for a form where changing the “country” dropdown updates the “state” dropdown and the “tax” label?
- Hands-on (Python). Implement
Strategyfor three string-similarity metrics, selected by name from a dict. Show how to add one at runtime. - Hands-on (TypeScript). Implement a state machine for a traffic light with a
transition(state, event)function. How would you enforce exhaustive handling at compile time? - Hands-on (Python). Write a generator that streams a large file’s lines, filters, and batches into lists of 100 without loading the file.
- Conceptual. Why is Visitor hard to extend with new node types? Give a language-feature alternative.
Solutions (sketch)
- Observer broadcasts; a Mediator holds the rule “country affects state list and tax”. Mediator suits multi-widget coordination logic.
METRICS = {"jaccard": f1, "levenshtein": f2};METRICS["new"] = f3; passMETRICS[name]to the caller.- Use a union of states and events, a
switchwith adefault: const _x: never = stateguard; the compiler errors on a missing case. def batches(path): batch=[]; for line in open(path): if keep(line): batch.append(line); if len(batch)==100: yield batch; batch=[]thenif batch: yield batch.- Adding a type requires adding a
visit_Xmethod to every existing visitor. Use polymorphic methods on the types themselves (open on types), or accept the cost knowingly.
Further reading
Section titled “Further reading”- Gamma, Helm, Johnson, Vlissides, Design Patterns (1994), behavioral patterns chapter.
- Robert Nystrom, Game Programming Patterns (2014, free online), excellent on Command, State, Observer.
- Philip Wadler, “The Expression Problem” (1998 note).
- Martin Fowler, Patterns of Enterprise Application Architecture (2002), for related application patterns.
- Eric Freeman and Elisabeth Robson, Head First Design Patterns (2nd ed., 2020).