GoF
GoF Patterns — Overview
"Each pattern describes a problem which occurs over and over again, and then describes the core of the solution to that problem." — Christopher Alexander, quoted in Design Patterns
"Patterns are not invented — they are discovered." — GoF
What GoF is
The Gang of Four — Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides — are the four architects who, in 1994, published Design Patterns: Elements of Reusable Object-Oriented Software. The book contains 23 patterns for typical OOP problems.
GoF is not a law. It is a vocabulary that architects use to talk to each other.
Three categories, 23 patterns
⚠️ Navigation: some patterns are combined into shared notes (because they illustrate one common idea) — Factory Method + Builder, Decorator + Facade, Composite + Proxy, Template Method + Chain of Responsibility + State. If two rows in a table link to the same
[[...]], that is intentional: "see the section in the combined note".
🏭 Creational (5) — about creating objects
How to create an object while hiding the construction details from the client.
| Pattern | Short | Modern Python |
|---|---|---|
| Factory Method (Creational Factory Builder) | A method creates objects, subclasses decide which | Usually @classmethod (User.from_db_row) |
| Abstract Factory (Creational Factory Builder) | A family of related factory methods | Rare, but possible |
| Builder | Step-by-step construction of a complex object | @dataclass(kw_only=True) is often enough |
| Prototype | Creation by cloning | copy.deepcopy — the language provides it |
| Singleton | One instance per program | Often an anti-pattern; modules are better |
🧱 Structural (7) — about composing classes
How to combine classes into larger structures.
| Pattern | Short | Modern Python |
|---|---|---|
| Adapter | A wrapper over an incompatible interface | Class-based or via Protocol |
| Bridge | Separates an abstraction from its implementation | Usually = composition + Protocol |
| Composite (Composite Proxy) | A tree where leaf and node share the same API | The standard form is through a Protocol |
| Decorator (Decorator Facade) | A wrapper that adds behaviour | Class-based or functools.wraps |
| Facade (Decorator Facade) | One simple API over a complex subsystem | An OrderSystem controller |
| Flyweight | Caching identical objects | Rare. Python caches small int (-5..256) and interned str automatically; sys.intern |
| Proxy (Composite Proxy) | A transparent intermediary with extra logic | Lazy initialisation, access control |
🎭 Behavioral (11) — about object interaction
How to distribute responsibility and connections between objects.
| Pattern | Short | Modern Python |
|---|---|---|
| Strategy | Interchangeable algorithms | Callable or Protocol |
| Observer Command | Subscriptions + notifications | Callable[..., None] or events |
| Command | An action as an object | Usually Callable, sometimes a class |
| Template Method (Template / CoR / State) | The base class sets the algorithm | ABC with concrete methods |
| Chain of Responsibility (Template / CoR / State) | A chain of handlers | A list of callables, middleware |
| State (Template / CoR / State) | Behaviour changes with state | Often Enum + match-case |
| Mediator | A coordinator for many objects | Usually a Pure Fabrication service |
| Iterator | Sequential access to a collection | __iter__ is built in |
| Visitor | Operations over a structure without changing it | @singledispatch or match-case |
| Memento | Save / restore state | Snapshot dataclass |
| Interpreter | A DSL with its own grammar | Very rare, in compilers |
Which of the 23 are really needed in modern Python?
✅ Often (must-know)
- Strategy — interchangeable algorithms. Basic and everywhere.
- Adapter — integration with legacy or third-party code. Irreplaceable.
- Decorator — adding behaviour (logging, caching, retry).
- Observer — event-driven, pub/sub, signal/slot.
- Template Method — in frameworks (Django Views and friends).
- Composite — tree structures (UI, AST, file systems).
- Facade — simplifying complex subsystems (controllers).
- Factory Method — creating objects with complex initialisation.
⚠️ Sometimes (use sparingly)
- Builder — for classes with 10+ parameters.
@dataclass(kw_only=True)is often enough. - Abstract Factory — for families of related objects. Rare in Python.
- Command — for undo/redo, queue systems. Usually
Callableis enough. - State — for complex FSMs. For simple ones,
match-case is better. - Chain of Responsibility — middleware chains (Django middleware).
- Proxy — lazy loading, access control.
❌ Anti-pattern or unnecessary
- Singleton — test-unfriendly, global state. Use a module as namespace instead.
- Flyweight — Python caches immutable types automatically (
sys.intern, smallint). Doing it by hand is almost never needed. - Prototype —
copy.deepcopydoes this for free. - Iterator — Python has
__iter__. No need to formalise. - Memento — for most cases,
dataclasses.replace()or a snapshot is enough. - Interpreter — only for DSL or language implementations. Not for everyday code.
- Visitor — for AST or complex structures. Prefer
match-case (Python 3.10+) or@singledispatch. - Mediator — a complex form of Pure Fabrication. Often confuses more than it helps.
- Bridge — in Python it collapses into Strategy, because abstraction and implementation are already separated through duck typing.
How to read each pattern in the next sections
Each pattern is described like this:
- Name (standard, from GoF).
- Problem — what hurts when you do not have it.
- Structure — a UML or pseudo-diagram.
- Python example — a concrete implementation.
- When to apply — real scenarios.
- When NOT to apply — anti-pattern / YAGNI.
- Pythonic alternatives — how often the language gives you the same idea for free.
A general anti-pattern: "pattern fever"
The worst mistake newcomers make with GoF:
"I know Strategy! I will put Strategy everywhere!"
The result is over-engineering, where a simple function becomes five classes. People call this "pattern fever". Symptoms:
- A simple expression wrapped in three levels of abstraction.
- 80% of interfaces have one implementation.
- Every change requires edits in six files.
- Reviewers ask, "why is this here?"
How to avoid it
- First, write it as it comes. Straightforward.
- If the code starts repeating, or something really does vary, refactor.
- Only then ask, "is this Strategy? Observer?". If the shape matches, formalise it with a pattern.
- YAGNI on top of everything. Every pattern adds complexity. Pay for it only where the benefit is real.
Rules of thumb
- Knowing a pattern means being able to recognise it where it naturally appears, not imposing it.
- Patterns do not replace SOLID / GRASP. They are concrete recipes that follow from those principles.
- Python covers half of GoF at the language level.
Callable,@dataclass,__iter__,match-case, type hints — these are built-in substitutes. - A name is a communication tool. If your design is Strategy, say "Strategy" in the review and everyone understands in two seconds.
- Do not fall in love with GoF. It is 1994. A lot has changed since then. Some patterns are artefacts of the Java world that had no first-class functions.
- Prefer simple code over a wrapper pattern. If
if/elifon 3 branches solves it honestly, it is not Strategy.
One-line summary
23 patterns are a vocabulary for recognising and discussing design. Do not "apply" them. Recognise them in your code. Most Python code uses 8-10 patterns regularly, the rest rarely, anti-patterns never.