Skip to content

Lesson 6 of 28Principles

Behavioral Patterns

Swap rules with Strategy, react with Observer, undo with Command, and tame workflows with state machines and middleware.

22 min read0/4 questions

Most bugs in business software are not in the maths. They are in who does what, when: a discount applied twice, an order shipped after it was cancelled, an auth check skipped on one route. Behavioral patterns are the standard ways to divide that work so each rule lives in one obvious place. You will use every one of these in real Python and TypeScript code.

Strategy: swappable rules

A Strategy is one interchangeable algorithm behind a common shape. Pricing is the classic case: regular price, Black Friday, bulk discount, member discount. Instead of one function with a growing if chain, each rule is its own function, and the caller picks one.

Python
from typing import Callable Order = list[tuple[int, int]] # (price_cents, qty)PricingRule = Callable[[int], int] def regular(subtotal: int) -> int: return subtotal def black_friday(subtotal: int) -> int: return subtotal - subtotal * 25 // 100 def member(subtotal: int) -> int: return subtotal - 500 if subtotal >= 5000 else subtotal RULES: dict[str, PricingRule] = {"regular": regular, "black_friday": black_friday, "member": member} def price(order: Order, rule: PricingRule) -> int: subtotal = sum(p * q for p, q in order) return rule(subtotal) order = [(2500, 2), (1000, 1)]for name, rule in RULES.items(): print(name, price(order, rule))
Output
Press Run (⌘ Enter) to see what happens.

price never changes when marketing invents a new promotion. You add one function to the table. When a strategy needs configuration (a percentage, a minimum), make a small class or a function that returns a function, like percent_off(15).

Observer: tell whoever is listening

An Observer setup has a subject that keeps a list of listeners and calls them when something happens. The subject does not know or care what the listeners do. Pub/sub, DOM events, Node's EventEmitter and React state stores are all this pattern.

Python
from typing import Callable class CartStore: def __init__(self): self.items: list[str] = [] self._listeners: list[Callable[[list[str]], None]] = [] def subscribe(self, fn: Callable[[list[str]], None]) -> Callable[[], None]: self._listeners.append(fn) return lambda: self._listeners.remove(fn) # unsubscribe def add(self, item: str) -> None: self.items.append(item) for fn in list(self._listeners): fn(self.items) cart = CartStore()unsubscribe_badge = cart.subscribe(lambda items: print("badge:", len(items)))cart.subscribe(lambda items: print("analytics: added", items[-1])) cart.add("mug")unsubscribe_badge()cart.add("cap")
Output
Press Run (⌘ Enter) to see what happens.

That subscribe returning an unsubscribe function is exactly the contract React's useSyncExternalStore expects, and it is how stores like Zustand re-render your components. Forgetting to unsubscribe is the classic Observer bug: a memory leak where dead components keep getting called.

Predict the outputTypeScript

What does this print?

const listeners: ((n: number) => void)[] = [];
const on = (fn: (n: number) => void) => listeners.push(fn);
const emit = (n: number) => listeners.forEach((fn) => fn(n));

let total = 0;
on((n) => (total += n));
emit(5);
on((n) => (total += n * 10));
emit(1);
console.log(total);
Need a nudge? Hints walk you through it.

Command: actions as objects (and undo)

A Command turns an action into a value you can store, queue, log or reverse. Give each command do() and undo(), keep a history stack, and undo/redo falls out almost for free. Redux actions, job queues and database migrations (upgrade / downgrade) are all commands.

Python
class Cart: def __init__(self): self.items: list[str] = [] class AddItem: def __init__(self, cart: Cart, item: str): self.cart, self.item = cart, item def do(self): self.cart.items.append(self.item) def undo(self): self.cart.items.remove(self.item) cart = Cart()history = []for item in ["mug", "cap", "bag"]: cmd = AddItem(cart, item) cmd.do() history.append(cmd)print(cart.items) history.pop().undo()print(cart.items)
Output
Press Run (⌘ Enter) to see what happens.

You will build the full undo and redo stack in the challenge at the end.

An order can be pending, paid, shipped, delivered, cancelled or refunded. Without structure, code sprinkles checks like if order.status != "shipped" everywhere, and someone eventually ships a cancelled order. A state machine lists every allowed transition in one table. Anything not in the table is rejected.

Order lifecycle
pendingpaidshippeddeliveredcancelledrefundedpaycancelshiprefunddeliverrefund

currentwaitingdone

Every order starts pending. From here only pay or cancel are legal.

1/4
Python
TRANSITIONS = { ("pending", "pay"): "paid", ("pending", "cancel"): "cancelled", ("paid", "ship"): "shipped", ("paid", "refund"): "refunded", ("shipped", "deliver"): "delivered", ("delivered", "refund"): "refunded",} def transition(state: str, event: str) -> str: try: return TRANSITIONS[(state, event)] except KeyError: raise ValueError(f"cannot {event} an order that is {state}") from None state = "pending"for event in ["pay", "ship", "cancel"]: try: state = transition(state, event) print(event, "->", state) except ValueError as e: print("rejected:", e)
Output
Press Run (⌘ Enter) to see what happens.

The GoF State pattern does the same with one class per state. A transition table is usually clearer in Python and TypeScript. For complex UI flows, libraries like XState take this further.

Quick check
What is the main advantage of the transition table over if checks spread across the codebase?
Need a nudge? A hint rules out a wrong answer.

Template method vs hooks

Template Method puts the fixed skeleton of an algorithm in a base class and lets subclasses fill in steps. Modern code often passes the varying steps in as callbacks (or hooks) instead, which avoids inheritance.

Python
from abc import ABC, abstractmethod class ReportExporter(ABC): # Template Method def export(self, rows: list[dict]) -> str: return "\n".join([self.header(rows), *map(self.row, rows)]) @abstractmethod def header(self, rows: list[dict]) -> str: ... @abstractmethod def row(self, r: dict) -> str: ... class CsvExporter(ReportExporter): def header(self, rows): return ",".join(rows[0]) def row(self, r): return ",".join(str(v) for v in r.values()) # Same skeleton with callbacks instead of a subclassdef export(rows: list[dict], header, row) -> str: return "\n".join([header(rows), *map(row, rows)]) rows = [{"sku": "MUG", "qty": 2}]print(CsvExporter().export(rows))print(export(rows, header=lambda rs: "| " + " | ".join(rs[0]) + " |", row=lambda r: "| " + " | ".join(map(str, r.values())) + " |"))
Output
Press Run (⌘ Enter) to see what happens.

Frameworks love Template Method: unittest.TestCase.setUp, Django class-based views, React class lifecycle methods. React hooks replaced that last one with exactly this callback style.

Chain of responsibility: middleware

In a Chain of Responsibility, a request passes through a line of handlers. Each one may handle it, change it, or pass it on to next. Web middleware is the textbook example.

A request through middleware
  1. loggingrecords method, path, duration
  2. rate limit429 if too many requests
  3. auth401 if no valid token
  4. route handlerthe actual business work

The request enters the first link. Logging starts a timer and calls next.

1/4
Python
from typing import Callable Handler = Callable[[dict], str]Middleware = Callable[[dict, Handler], str] def logging_mw(req: dict, next: Handler) -> str: res = next(req) print(f"{req['path']} -> {res}") return res def auth_mw(req: dict, next: Handler) -> str: if "token" not in req: return "401" return next(req) def handler(req: dict) -> str: return "200" def build(chain: list[Middleware], final: Handler) -> Handler: for mw in reversed(chain): final = (lambda mw, nxt: lambda req: mw(req, nxt))(mw, final) return final app = build([logging_mw, auth_mw], handler)app({"path": "/orders", "token": "t"})app({"path": "/orders"})
Output
Press Run (⌘ Enter) to see what happens.
Put it in order5 steps

A request hits an app with middleware [cors, logging, auth] and a route handler. Order the code that runs first to last, assuming everything passes.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Iterator, briefly

You met Iterator in the overview: Python's __iter__/generators and JavaScript's Symbol.iterator/function*. In app code it shines for paginated APIs: callers write a plain for loop and never see page tokens. You will build exactly that kind of generator pattern again when streaming events later in this track.

Match the pairs0/5 matched

Match each feature request to the pattern.

Choose an item, then its match on the other side.
ChallengeEasy

Pricing strategies

Implement price(order, strategy) that returns the order total in cents after applying a named pricing strategy. Keep one small function per strategy in a lookup table, not an if chain inside price.

An order is {"items": [{"price": 1000, "qty": 2}, ...]}. The subtotal is the sum of price * qty.

StrategyRule
"regular"the subtotal
"black_friday"25% off (round the discount down to a whole cent)
"bulk"10% off (discount rounded down) when the total quantity is 10 or more
"member"500 off when the subtotal is at least 5000
anything elsesame as "regular"
price({"items": [{"price": 999, "qty": 1}]}, "black_friday")  ->  750   (discount 249)
def price(order: dict, strategy: str) -> int: # Compute the subtotal, then look up and apply the strategy function. pass
ChallengeMedium

Undo and redo with commands

Commands like AppendText (given in the starter) have do() and undo(). Build an UndoStack that runs them and supports undo and redo.

  • execute(cmd): run cmd.do(), remember it for undo, and clear the redo history (a new action after an undo makes the old future unreachable, like in every editor)
  • undo(): undo the most recent command and make it redoable. Return True / true if something was undone, False / false if there was nothing to undo
  • redo(): re-run the most recently undone command. Same return rule
  • can_undo() / can_redo() (TypeScript: canUndo() / canRedo()) return booleans
doc = Document(); stack = UndoStack()
stack.execute(AppendText(doc, "Hello"))
stack.execute(AppendText(doc, " world"))
stack.undo()   # doc.text == "Hello"
stack.redo()   # doc.text == "Hello world"
class Document: def __init__(self): self.text = "" class AppendText: """A command: knows how to do and undo one edit.""" def __init__(self, doc: Document, chunk: str): self.doc = doc self.chunk = chunk def do(self) -> None: self.doc.text += self.chunk def undo(self) -> None: self.doc.text = self.doc.text[: len(self.doc.text) - len(self.chunk)]class UndoStack: def __init__(self): pass def execute(self, cmd) -> None: pass def undo(self) -> bool: pass def redo(self) -> bool: pass def can_undo(self) -> bool: pass def can_redo(self) -> bool: pass
Key terms
strategy
One of several interchangeable algorithms behind the same shape, chosen by the caller. Often just a function.
observer
A subject keeps a list of listeners and notifies them of changes; listeners can subscribe and unsubscribe.
command
An action stored as an object with do and undo, so it can be queued, logged or reversed.
state machine
A fixed set of states plus a table of allowed transitions; anything not listed is rejected.
template method
A base class fixes the steps of an algorithm and subclasses fill in some of them.
chain of responsibility
A request passes through a line of handlers, each of which can handle it or pass it on. Middleware.