| 01 | Iterator | loop over items without knowing how they’re stored | a separate object returns one item per next() | Django, Jinja2 | your object holds items others loop over | built in; write __iter__ as a generator |
|---|
| 02 | Generator pipelines | process a stream bigger than memory | generators pull from generators, one item at a time | requests, Django | input is large, endless or slow | functions with yield, and itertools |
|---|
| 03 | Context managers | cleanup must run even when the code raises | with calls __enter__() before and __exit__() after | contextlib, pytest | something must be released or undone | built in; @contextmanager and ExitStack |
|---|
| 04 | Strategy | swap an algorithm without changing the caller | pass the algorithm in behind a shared interface | requests, Django | several ways to do one step exist | usually a function: key=, auth= |
|---|
| 05 | Template Method | fixed steps, a few of which vary | a base method runs the steps and calls hooks | logging, Django | variants must keep the order and the locking | inheritance; abstractmethod for required hooks |
|---|
| 06 | Observer | react to an event without the sender knowing you | listeners connect to a signal the sender sends | blinker, Flask | code in other packages must react | a list of callables, or blinker |
|---|
| 07 | Plugin hooks | installed packages must extend a program | named hooks; every implementation is called | pluggy, pytest | extensions come from packages you don’t control | pluggy and entry points |
|---|
| 08 | Command | an action to queue, print or undo | the action becomes an object with its arguments | Alembic, Django | actions are stored, previewed or reversed | functools.partial; a class for undo |
|---|
| 09 | Chain of Responsibility | many checks, any of which may answer | each handler answers or passes to the next | Starlette, urllib | independent checks share every request | middleware, or a list of functions |
|---|
| 10 | State | behaviour depends on a mode | delegate to the current state; a table moves it | h11 | illegal moves between modes must be refused | an Enum and a dict of allowed moves |
|---|
| 11 | Visitor | new operations over a fixed tree | a visit_ method per node type, found by name | Jinja2, ast | operations change more often than node types | ast.NodeVisitor; singledispatch for values |
|---|
| 12 | Memento | save and restore state you mustn’t read | the object makes and restores its own snapshot | random, Django | undo, checkpoints, replays | __getstate__ and __setstate__ |
|---|
| 13 | Mediator | rules that span several parts | one object owns the rules; parts talk only to it | Django, DRF | parts would otherwise reference each other | the form, controller or service you have |
|---|
| 14 | Interpreter | a small language users write in | parse to a tree, evaluate each node type | jmespath, re | options can’t express what users need | ast.parse() plus your own evaluator |
|---|