Skip to content

Lesson 8 of 9 · 24m

Behavioral Patterns: Strategy, Command, Observer, Iterator

Behavioral patterns map cleanly onto Python's functions, generators, events, and context managers — use the mechanism the language already gives you before building class ceremony.

Behavioral patterns describe how objects collaborate. Python's trick is that many collaborations are already language features. Strategy is often just a function argument. Iterator is a generator. Command can be a closure. The design skill is recognizing when the language feature is sufficient and when the extra object earns its keep.

Strategy: pass behavior, not a family tree

def total_price(items, pricing):
    return sum(pricing(item) for item in items)
total = total_price(cart.items, lambda item: item.cents * item.quantity)

pricing is a strategy. No abstract PricingStrategy base class is required unless implementations need shared state or lifecycle. When the strategy grows stateful — rate limiting, caching, metrics — then a small object with a method is appropriate. Start with the function; promote it when behavior gains structure.

Command: make work explicit and reversible

@dataclass(frozen=True)
class ResizeImage:
    path: Path
    width: int
    height: int
    def execute(self, editor) -> None:
        editor.resize(self.path, self.width, self.height)

Commands are valuable when you need queues, retries, audit logs, undo, or serialization. A job queue message is a command: explicit inputs, no hidden context, executable later. For a button callback in a small app, a plain function is simpler. Do not create command classes because a book told you every action needs one.

Observer: events need ownership and ordering

class EventBus:
    def __init__(self):
        self._subscribers = defaultdict(list)
    def subscribe(self, event_type, handler):
        self._subscribers[event_type].append(handler)
    def publish(self, event):
        for handler in self._subscribers[type(event)]:
            handler(event)

Observer decouples producers from consumers, but it also hides control flow. Questions that matter: Are handlers synchronous? Can they fail? Do they run in order? Can a handler publish more events? Answer these deliberately. In web services, explicit use-case orchestration is often easier to debug than a pile of events firing in import order.

Iterator: generators are the native implementation

def read_batches(rows, size=1000):
    batch = []
    for row in rows:
        batch.append(row)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch

This is the Iterator pattern without an iterator object hierarchy. Generators give lazy streaming, backpressure-friendly loops, and cleanup through generators' close semantics. They are one of Python's great gifts; use them before inventing collection abstractions.

Field notes

  • Event systems need dead-letter handling if delivery matters; silent handler exceptions turn observability into archaeology.
  • Generators are single-use; returning one where callers expect reusable iteration causes empty second passes.

Was this lesson helpful?

Sign in to rate