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.
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".
1977
A Pattern Language
Architect Christopher Alexander catalogues recurring solutions for buildings and towns. Software people borrow the idea.
1987
Patterns reach software
Kent Beck and Ward Cunningham present patterns for user interfaces at the OOPSLA conference.
1994
The Gang of Four book
Gamma, Helm, Johnson and Vlissides publish 'Design Patterns', with 23 patterns written for C++ and Smalltalk.
2002
Enterprise patterns
Martin Fowler's 'Patterns of Enterprise Application Architecture' names Repository, Unit of Work and friends.
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.
Three families: making objects, combining them, and dividing work between them.
Match each pattern to its family.
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.
| Pattern | Where you have already seen it |
|---|---|
| Iterator | Every for loop, Python generators, JS for...of |
| Decorator | Python @lru_cache, @app.get(...), logging wrappers |
| Observer | addEventListener, React state subscriptions, Node EventEmitter |
| Strategy | sorted(users, key=...), array.sort((a, b) => ...) |
| Chain of Responsibility | FastAPI and Express middleware |
| Builder | SQLAlchemy select(User).where(...).order_by(...) |
| Adapter | A wrapper class around a payment or email SDK |
| Facade | requests.get(url) hiding sockets, TLS and HTTP parsing |
| Singleton | A 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.
Press Run (⌘ Enter) to see what happens.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.
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.
Press Run (⌘ Enter) to see what happens.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.
What does this print?
def gen():
print("start")
yield 1
print("middle")
yield 2
g = gen()
print(next(g))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.
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.
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.
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.
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)])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().
Press Run (⌘ Enter) to see what happens.| Active record | Data mapper | |
|---|---|---|
| Example | Django ORM, Rails | SQLAlchemy ORM, Hibernate, Doctrine |
| Domain object knows the DB? | Yes, it is the row | No |
| Speed to build CRUD | Very fast | More setup |
| Testing rules without a DB | Harder | Easy: plain objects |
| Fits | CRUD-heavy apps, admin tools | Complex 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.
Order.refund() method calls self.save() and Payment.objects.create(...). Testing refund rules now needs a database. Which statement is most accurate?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.
| Problem | Pattern | What it does |
|---|---|---|
| A dependency hangs | Timeout | Give up after a fixed time instead of waiting forever |
| A call fails for a moment | Retry with backoff and jitter | Try again, waiting longer each time, with randomness so clients do not retry in sync |
| A dependency is down and retries make it worse | Circuit breaker | After repeated failures, fail fast for a while, then let one trial call through |
| One slow dependency uses up all threads | Bulkhead | Give each dependency its own limited pool, so one cannot sink the rest |
| A retry might charge twice | Idempotency key | The client sends a unique key; the server stores the result and returns it on repeats |
| Save data and publish an event atomically | Transactional outbox | Write the event in the same transaction, publish it from a relay |
| A workflow spans several services | Saga | Local 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 each production problem to the pattern that addresses it.
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).
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:
- The pain: what was going wrong in real code. "Every new shipping carrier meant editing a 200-line
ifchain, and two carriers broke in one release." - The pattern and the shape: "I made each carrier a strategy behind a
quote(parcel)interface, chosen from a dict by carrier code." - The result: something measurable or concrete. "Adding DHL became one new file and one test file. No more regressions in other carriers."
- 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 the parts of a strong answer to 'Which design patterns have you used?' in a sensible order.
- Tap the steps below in the right order.
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.
- 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.