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.
type Order = { priceCents: number; qty: number }[];type PricingRule = (subtotal: number) => number;const rules: Record<string, PricingRule> = { regular: (s) => s, blackFriday: (s) => s - Math.floor((s * 25) / 100), member: (s) => (s >= 5000 ? s - 500 : s),};function price(order: Order, rule: PricingRule): number { const subtotal = order.reduce((sum, i) => sum + i.priceCents * i.qty, 0); return rule(subtotal);}const order: Order = [{ priceCents: 2500, qty: 2 }, { priceCents: 1000, qty: 1 }];for (const [name, rule] of Object.entries(rules)) console.log(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.
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.
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.
You will build the full undo and redo stack in the challenge at the end.
State machine: only legal moves
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
currentwaitingdone
Every order starts pending. From here only pay or cancel are legal.
1/4
Python
12345678910111213141516171819202122
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 Nonestate = "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.
TypeScript
12345678910111213141516171819202122232425
type State = "pending" | "paid" | "shipped" | "delivered" | "cancelled" | "refunded";type Event = "pay" | "cancel" | "ship" | "deliver" | "refund";const transitions: Partial<Record<State, Partial<Record<Event, State>>>> = { pending: { pay: "paid", cancel: "cancelled" }, paid: { ship: "shipped", refund: "refunded" }, shipped: { deliver: "delivered" }, delivered: { refund: "refunded" },};function transition(state: State, event: Event): State { const next = transitions[state]?.[event]; if (!next) throw new Error(`cannot ${event} an order that is ${state}`); return next;}let state: State = "pending";for (const event of ["pay", "ship", "cancel"] as Event[]) { try { state = transition(state, event); console.log(event, "->", state); } catch (e) { console.log("rejected:", (e as Error).message); }}
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.
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
loggingrecords method, path, duration
rate limit429 if too many requests
auth401 if no valid token
route handlerthe actual business work
The request enters the first link. Logging starts a timer and calls next.
1/4
Python
1234567891011121314151617181920212223242526
from typing import CallableHandler = 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 resdef 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 finalapp = build([logging_mw, auth_mw], handler)app({"path": "/orders", "token": "t"})app({"path": "/orders"})
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.
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.
Strategy
Rule
"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
def price(order: dict, strategy: str) -> int: # Compute the subtotal, then look up and apply the strategy function. pass
⌘ Enter
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