Skip to content

Lesson 3 of 28Principles

Design Patterns Overview

The GoF families, the enterprise and resilience patterns you meet at work, and how to talk about patterns in interviews.

25 min read0/8 questions

When a senior engineer says "wrap the SDK in an adapter" or "make pricing a strategy", they are compressing a paragraph of design into one word. Design patterns are that shared vocabulary. Knowing them lets you read codebases faster, explain your designs in reviews, and answer the "which pattern would you use here?" question that shows up in mid-level interviews.

What a pattern is

A design pattern is a named, reusable shape of solution to a problem that keeps coming back. It is not a library and not code you copy. It is closer to a recipe: "when you need X, people usually arrange objects like Y, and here are the trade-offs".

Where patterns came from
  1. 1977

    A Pattern Language

    Architect Christopher Alexander catalogues recurring solutions for buildings and towns. Software people borrow the idea.

  2. 1987

    Patterns reach software

    Kent Beck and Ward Cunningham present patterns for user interfaces at the OOPSLA conference.

  3. 1994

    The Gang of Four book

    Gamma, Helm, Johnson and Vlissides publish 'Design Patterns', with 23 patterns written for C++ and Smalltalk.

  4. 2002

    Enterprise patterns

    Martin Fowler's 'Patterns of Enterprise Application Architecture' names Repository, Unit of Work and friends.

  5. 2010s

    Patterns melt into languages

    First-class functions, generators and decorators make many classic patterns a one-liner in Python and JavaScript.

The 1994 authors became known as the Gang of Four (GoF). Their book shaped two decades of object-oriented design, and its pattern names are still what people use today.

The three families

The GoF patterns are grouped by the kind of problem they solve:

  • Creational: how objects get made. Hide which class you build, or build a complex object step by step.
  • Structural: how objects fit together. Wrap, combine, or simplify existing pieces.
  • Behavioral: how objects talk and share work. Swap algorithms, react to events, pass requests along.
The 23 GoF patterns
Design patternsFactory MethodAbstract FactoryBuilderPrototypeSingletonCreationalmaking objectsAdapterBridgeCompositeDecoratorFacadeFlyweightProxyStructuralcombining objectsStrategyObserverCommandStateTemplate MethodChain of ResponsibilityIteratorMediatorMementoVisitorInterpreterBehavioraldividing workroot

Three families: making objects, combining them, and dividing work between them.

1/5
Match the pairs0/3 matched

Match each pattern to its family.

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

The ones you will actually meet

The GoF book assumed a language where everything must be a class. Python and TypeScript are more relaxed, so some patterns turn into a feature you already use.

PatternWhere you have already seen it
IteratorEvery for loop, Python generators, JS for...of
DecoratorPython @lru_cache, @app.get(...), logging wrappers
ObserveraddEventListener, React state subscriptions, Node EventEmitter
Strategysorted(users, key=...), array.sort((a, b) => ...)
Chain of ResponsibilityFastAPI and Express middleware
BuilderSQLAlchemy select(User).where(...).order_by(...)
AdapterA wrapper class around a payment or email SDK
Facaderequests.get(url) hiding sockets, TLS and HTTP parsing
SingletonA Python module (imported once, shared everywhere)

Functions replace whole patterns

In classic Java-style code, Strategy means an interface plus one class per algorithm. When functions are values you can pass around (first-class functions), the strategy is just a function.

Python
# Class-heavy Strategy, the way the 1994 book shows itclass ByPrice: def key(self, p): return p["price"] class ByName: def key(self, p): return p["name"] products = [{"name": "Mug", "price": 12}, {"name": "Cap", "price": 20}, {"name": "Bag", "price": 8}]print([p["name"] for p in sorted(products, key=ByPrice().key)]) # Idiomatic Python: the strategy IS the functionprint([p["name"] for p in sorted(products, key=lambda p: p["name"])])
Output
Press Run (⌘ Enter) to see what happens.

The same thing happens to Command (an action stored as a value: a function or a plain object like a Redux action) and to Template Method (pass a callback instead of subclassing). You still need the idea of each pattern. You rarely need its 1994 class diagram.

Quick check
Why does Strategy usually shrink to a plain function in Python and TypeScript?
Need a nudge? A hint rules out a wrong answer.

Iterators and generators are built in

The Iterator pattern gives you items one at a time without exposing how they are stored. Both languages bake it in: a generator function pauses at each yield and resumes when the loop asks for the next item. That makes it ideal for paging through API results or streaming a huge export without loading everything into memory.

Python
def batches(rows, size): for start in range(0, len(rows), size): print(f" (building batch at {start})") yield rows[start:start + size] for batch in batches(["a", "b", "c", "d", "e"], 2): print("send", batch)
Output
Press Run (⌘ Enter) to see what happens.

Notice the output interleaves: each batch is built just before it is used. That laziness is the point.

Predict the outputPython

What does this print?

def gen():
  print("start")
  yield 1
  print("middle")
  yield 2

g = gen()
print(next(g))
Need a nudge? Hints walk you through it.

The enterprise patterns you meet at work

The GoF patterns describe objects inside a program. The patterns you will name most often in a backend job come from Fowler's 2002 enterprise book, and they describe how a business application is put together. You will see these names in pull requests, design docs and framework docs every week.

Enterprise patterns in one request
  1. DTOrequest and response shapes at the edge: Pydantic models, Zod schemas
  2. Service layerone method per use case: place_order, refund_order
  3. Domain model + Specificationentities with rules, and named, combinable business conditions
  4. Repositorya collection-like interface: get, add, list_overdue
  5. Unit of Work + Data Mappertracks changes, maps objects to rows, commits once

A DTO (data transfer object) is a plain shape that crosses a boundary. It carries data, never behaviour, so the public API can change separately from the tables.

1/5

The Layered Architecture lesson shows repository, service layer and DTO working together in code. Two are worth a closer look here.

Unit of work. Without it, every save() is its own write, and a use case that changes three objects can fail after the second. A unit of work collects the changes and commits them together. You rarely write one yourself: SQLAlchemy's Session, Entity Framework's DbContext and Hibernate's session are all units of work. When you call session.commit(), the session works out which objects are new or changed and issues the SQL in one transaction.

Specification. Business conditions tend to get copied. "Overdue and not disputed" shows up in the collections job, the dashboard and the reminder email, each written slightly differently. A specification gives the condition a name and lets you combine conditions with and, or and not.

Python
class Spec: def __init__(self, test): self.test = test def __call__(self, item): return self.test(item) def __and__(self, other): return Spec(lambda x: self(x) and other(x)) def __or__(self, other): return Spec(lambda x: self(x) or other(x)) def __invert__(self): return Spec(lambda x: not self(x)) is_overdue = Spec(lambda inv: inv["days_late"] > 30)is_disputed = Spec(lambda inv: inv["disputed"])send_to_collections = is_overdue & ~is_disputed invoices = [ {"id": 1, "days_late": 45, "disputed": True}, {"id": 2, "days_late": 40, "disputed": False}, {"id": 3, "days_late": 5, "disputed": False},]print([inv["id"] for inv in invoices if send_to_collections(inv)])
Output
Press Run (⌘ Enter) to see what happens.

In Python and TypeScript a specification is often just a named predicate function. The full pattern earns its keep when the same condition must also become a SQL WHERE clause, for example a spec that can both test an object in memory and add a filter to a query. Without that need, a well-named function is enough.

Predict the outputPython

What does this print?

# Spec is the class from the block above
is_overdue = Spec(lambda inv: inv["days_late"] > 30)
is_disputed = Spec(lambda inv: inv["disputed"])
remind = ~is_overdue | is_disputed

invoices = [
  {"id": 1, "days_late": 45, "disputed": True},
  {"id": 2, "days_late": 40, "disputed": False},
  {"id": 3, "days_late": 5, "disputed": False},
]
print([inv["id"] for inv in invoices if remind(inv)])
Need a nudge? Hints walk you through it.

Active record vs data mapper

There are two ways an ORM can connect objects to tables, and the one your framework picked shapes the whole codebase.

Active record: each object wraps a row and knows how to save itself. user.save(), User.objects.filter(...). Django's ORM and Rails' ActiveRecord work this way.

Data mapper: domain objects are plain and know nothing about the database. A separate mapper (with a unit of work) loads and saves them. SQLAlchemy's ORM works this way: you session.add(user) and session.commit().

Python
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, plan TEXT)") # ---- Active record: the object saves itself, one write per save()class ActiveUser: def __init__(self, name, plan="free"): self.id, self.name, self.plan = None, name, plan def save(self): if self.id is None: cur = conn.execute("INSERT INTO users (name, plan) VALUES (?, ?)", (self.name, self.plan)) self.id = cur.lastrowid else: conn.execute("UPDATE users SET plan = ? WHERE id = ?", (self.plan, self.id)) conn.commit() print(f" saved {self.name} ({self.plan})") print("active record:")ada = ActiveUser("Ada")ada.save()ada.plan = "pro"ada.save() # ---- Data mapper + unit of work: plain objects, persistence elsewhereclass User: # no SQL in here, easy to test def __init__(self, name, plan="free"): self.id, self.name, self.plan = None, name, plan def upgrade(self): self.plan = "pro" class UnitOfWork: def __init__(self, conn): self.conn, self.new = conn, [] def add(self, user): self.new.append(user) def commit(self): with self.conn: # one transaction for everything for user in self.new: cur = self.conn.execute("INSERT INTO users (name, plan) VALUES (?, ?)", (user.name, user.plan)) user.id = cur.lastrowid print(f" committed {len(self.new)} users in one transaction") self.new.clear() print("data mapper + unit of work:")uow = UnitOfWork(conn)grace = User("Grace")grace.upgrade()uow.add(grace)uow.add(User("Linus"))uow.commit() print(conn.execute("SELECT name, plan FROM users ORDER BY id").fetchall())
Output
Press Run (⌘ Enter) to see what happens.
Active recordData mapper
ExampleDjango ORM, RailsSQLAlchemy ORM, Hibernate, Doctrine
Domain object knows the DB?Yes, it is the rowNo
Speed to build CRUDVery fastMore setup
Testing rules without a DBHarderEasy: plain objects
FitsCRUD-heavy apps, admin toolsComplex domains with many rules

Neither is wrong. Active record is a great fit when objects really are rows with a bit of validation. The pain starts when rules get complex: business logic ends up in model methods that touch the database, tests need a database, and save() calls scattered across the code make transaction boundaries hard to see. Teams on Django handle this by keeping rules in plain functions or service modules and treating models as persistence. Teams on SQLAlchemy pay more setup to keep the domain clean. In TypeScript, Prisma and Drizzle are neither pattern exactly: they are typed query clients that return plain objects, so you build your own repositories on top if you want them.

Quick check
Your Django app's Order.refund() method calls self.save() and Payment.objects.create(...). Testing refund rules now needs a database. Which statement is most accurate?
Need a nudge? A hint rules out a wrong answer.

Resilience and integration patterns: a map

Once your code talks to other services over a network, a second family of patterns matters more than most of the GoF list. They have names you will hear in every incident review. Here is the map. The System Design course covers each one properly.

ProblemPatternWhat it does
A dependency hangsTimeoutGive up after a fixed time instead of waiting forever
A call fails for a momentRetry with backoff and jitterTry again, waiting longer each time, with randomness so clients do not retry in sync
A dependency is down and retries make it worseCircuit breakerAfter repeated failures, fail fast for a while, then let one trial call through
One slow dependency uses up all threadsBulkheadGive each dependency its own limited pool, so one cannot sink the rest
A retry might charge twiceIdempotency keyThe client sends a unique key; the server stores the result and returns it on repeats
Save data and publish an event atomicallyTransactional outboxWrite the event in the same transaction, publish it from a relay
A workflow spans several servicesSagaLocal steps with compensating actions instead of one big transaction

Timeouts, retries, circuit breakers and bulkheads are in the "Timeouts, Retries, and Circuit Breakers" lesson. Outbox and sagas are introduced in the Event-Driven Architecture lesson here and go deeper in "Sagas, Outbox, and Two-Phase Commit". Idempotency keys appear in the "Design a Payment System" case study.

Two things connect them. First, retries without idempotency are dangerous: every retry pattern assumes the receiver can safely see the same request twice. Second, they compose in a set order. A typical outbound call is wrapped as timeout inside retry inside circuit breaker, so each attempt is bounded, failed attempts retry, and a dependency that keeps failing trips the breaker so you stop retrying it.

Match the pairs0/5 matched

Match each production problem to the pattern that addresses it.

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

Patterns are tools, not goals

Pattern overuse is a real smell. A UserManagerFactoryProvider around a two-line function makes code harder to read, not easier. Reach for a pattern when you feel the specific pain it fixes: a growing if chain (Strategy), an SDK leaking into your business code (Adapter), a long constructor call (Builder).

Quick check
Which situation most justifies introducing a pattern?
Need a nudge? A hint rules out a wrong answer.

Talking about patterns in an interview

"Which design patterns have you used?" is a common opener in mid-level interviews, and most candidates answer it badly by reciting names. The interviewer is not checking your memory. They want to know whether you can spot a design problem and pick a fitting fix, and whether you know what it cost.

A strong answer has four parts, for each of one or two patterns:

  1. The pain: what was going wrong in real code. "Every new shipping carrier meant editing a 200-line if chain, and two carriers broke in one release."
  2. The pattern and the shape: "I made each carrier a strategy behind a quote(parcel) interface, chosen from a dict by carrier code."
  3. The result: something measurable or concrete. "Adding DHL became one new file and one test file. No more regressions in other carriers."
  4. The trade-off: what it cost or when you would not do it. "It is one more indirection. For two carriers I would have kept the if."

Good choices to talk about are the ones you can defend with a real story: Strategy, Adapter around a vendor SDK, Repository, Observer or pub/sub, Decorator for cross-cutting behaviour, Builder for test data. Avoid opening with Singleton. Interviewers often follow up with "what are its downsides?", and the honest answer (hidden global state, hard to test) undercuts your story.

Expect follow-ups like "how is that different from X?" (Strategy vs State, Adapter vs Facade, Decorator vs Proxy) and "would you use it again?". The pattern lessons in this track give you the one-line differences.

Put it in order4 steps

Put the parts of a strong answer to 'Which design patterns have you used?' in a sensible order.

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

Lazy pages with a generator

Write a generator pages(items, size) that yields lists of up to size items at a time. This is the Iterator pattern, built into the language.

list(pages([1, 2, 3, 4, 5], 2))  ->  [[1, 2], [3, 4], [5]]
list(pages([], 3))               ->  []

It must work on any iterable (a list, a range, another generator) and be lazy: getting the first page must only read the first size items from the source, not the whole thing. That is what lets you stream a million-row export.

You can assume size >= 1.

def pages(items, size: int): # Collect items into a page and yield it each time it is full. pass
Key terms
design pattern
A named, reusable solution shape for a recurring design problem, with known trade-offs.
Gang of Four
The four authors of the 1994 book 'Design Patterns', which catalogued 23 object-oriented patterns.
creational / structural / behavioral
The three GoF families: making objects, combining objects, and dividing work between objects.
first-class function
A function that can be stored, passed and returned like any value, which replaces many class-based patterns.
generator
A function that yields items lazily, one at a time. The language's built-in Iterator pattern.
unit of work
Tracks the objects changed during one business action and writes them all in a single transaction.
specification
A named, combinable business condition, such as overdue and not disputed, that can be reused and tested.
active record
An ORM style where each object wraps a row and saves itself, as in Django and Rails.
data mapper
An ORM style where plain domain objects are loaded and saved by a separate mapper, as in SQLAlchemy.
circuit breaker
A wrapper that stops calling a failing dependency for a while and fails fast instead.