The 23 names that gave the trade its vocabulary: you speak GoF without knowing it, like prose.
Why this book
The scenery first. A design pattern is a reusable solution to a design problem that keeps coming back, with a name so you can talk about it. This book, Design Patterns: Elements of Reusable Object-Oriented Software, is the founding catalog: 23 patterns, published in 1994 by four authors (Gamma, Helm, Johnson, Vlissides), hence their "Gang of Four" nickname and the "GoF" abbreviation you will meet everywhere. My Head First Design Patterns notes (HFDP, the illustrated, playful textbook that teaches these same patterns) kept pointing at this book: HFDP is the fun retelling, this is the source.
It reads like a dictionary because it is one: the catalog, in chapters 3 to 5, gives one entry per pattern, in a fixed format, sorted into three families: creational (making objects), structural (assembling them), behavioral (making them collaborate). But chapter 1 and the chapter 2 case study are real prose, and they contain the two principles everything else hangs from.
The ideas that follow answer six questions:
- What is a pattern, and which two principles does it rest on? (ideas 1 and 2)
- How do you choose: what must be able to vary? (idea 3)
- What does it look like in practice? (ideas 4 and 5, the Lexi editor and Observer)
- How do you tell apart two patterns that look alike? (idea 6)
- How do you use them without overdoing it? (idea 7)
- What does the book say about itself? (idea 8)
The ideas that stick
1A pattern is, first of all, a name
The book starts with the word itself. It borrows the idea from Christopher Alexander, an architect of buildings: a pattern "describes a problem which occurs over and over again in our environment, and then describes the core of the solution" (ch. 1). Four mandatory elements: a name, a problem, a solution, the consequences. And the authors insist the name is the hardest to find: "Finding good names has been one of the hardest parts of developing our catalog" (ch. 1).
Why so much fuss about names? Compression. Before: "you know, the object that wraps another one and adds scrolling without the wrapped one knowing". After: "a Decorator" (one of the book's 23 patterns: an object that wraps another one to add a behavior). Without a name, you have to redescribe the structure piece by piece in every sentence, and the discussion stays stuck in class details. With a name, you talk about the idea. That is the actual product of the book: not the techniques (they existed), the shared vocabulary. What remains is what these names cover: chapter 1 answers with two principles.
2The two commandments everything hangs from
Chapter 1 sets two principles in bold. You will find them again in the patterns of the next ideas.
- "Program to an interface, not an implementation" (ch. 1): never declare a variable as an instance of a concrete class. Depend on the abstract type, so the concrete one can change without your code having to follow.
- "Favor object composition over class inheritance" (ch. 1): inheriting is "white-box" reuse: the subclass sees the parent's guts, and "any change in the parent's implementation will force the subclass to change". Composing is "black-box" reuse: you assemble parts of which you only see the interface, the contract.
Both commandments, before and after, on a case we have all written:
// ✗ BEFORE: concrete class + inheritance to vary
class Report {
private $export = new MySQLExport();
// frozen concrete
}
class PdfReport extends Report { ... }
class EncryptedPdfReport extends PdfReport { ... }
// inheritance: the tree runs away
// ✓ AFTER: one interface + parts you assemble
class Report {
public function __construct(
private Export $export,
// 3 exports: MySQL, S3, CSV
private Format $format,
// 3 formats: PDF, HTML, encrypted
) {}
}
new Report(new S3Export(), new EncryptedPdf());
// combine, no tree
The before stacks two flaws, one per principle. The export is hard-wired (new MySQLExport()): that is the concrete class the first principle forbids. And every variant goes through a subclass (PDF, encrypted PDF, encrypted compressed PDF...): that is the inheritance the second one discourages. So you need one subclass per combination. The after assembles independent parts, and the count changes:
| Inheritance | Composition | |
|---|---|---|
| 3 exports × 3 formats | 9 classes | 6 classes |
| A 4th format tomorrow | 3 more classes | 1 more class |
The authors admit the trap themselves: they observe that "designers overuse inheritance as a reuse technique, and designs are often made more reusable (and simpler) by depending more on object composition" (ch. 1).
Thirty years later, "fragile base classes" (a parent class nobody dares touch anymore, because its subclasses break) proved them right. The sign to look for in your own code: a parent class that scares everyone off. That is when composition would have held up better.
These two principles say how to assemble. What remains is the question that decides what goes into a part of its own: what must be able to vary?
3One question behind 23 answers: what must be able to vary?
The book's selection guide, the section that sorts patterns by what they let you vary, hides its deepest idea: each pattern encapsulates one thing that changes, that is, locks it inside an object of its own, so the rest doesn't have to. Five examples, each time the definition then an everyday case:
- Strategy: a family of interchangeable calculations behind one interface. What gets encapsulated is the algorithm. Your shipping fees: standard post, express or store pickup, three different calculations for the same question "how much?", swappable without touching the cart:
interface ShippingFee { compute(cart): float } class StandardPost implements ShippingFee { compute(cart) { /* carrier price grid */ } } class StorePickup implements ShippingFee { compute(cart) { return 0 } } // shipping = StandardPost or StorePickup, depending on the // customer's choice total = cart.total() + shipping.compute(cart) - State: an object that changes behavior with its internal state, as if it "changed class". An e-commerce order: the same "Cancel" button does completely different things depending on whether the order is in the cart, paid, or shipped:
It looks like Strategy (a delegate object you swap). The difference: in Strategy, you pick the part and it stays. In State, the object itself swaps it at each stage of its life.// the order CARRIES its state: an object, replaced at each // step of its life class Order { // starting state state = new InCart() pay() { // changing state = swapping the object this.state = new Paid() } ship() { this.state = new Shipped() } cancel() { // delegates to the current state this.state.cancel() } } // each state knows what "cancel" means for itself class InCart { cancel() { emptyCart() } } class Paid { cancel() { refund() } } class Shipped { cancel() { requestReturn() } } order.pay() order.cancel() // → refunds, because the current state is Paid. // Zero if. - Iterator: a way to walk a collection without knowing its internal structure:
The day the array becomes an SQL query, the loop does not move one line: that is what the pattern buys. The// three sources, stored totally differently orders = [o1, o2, o3] // in-memory array orders = Order::fromDatabase() // SQL result, row by row orders = readHugeCsv('orders.csv') // generator: never all in RAM // the SAME loop works for all three: each source knows how // to walk itself foreach (orders as o) { process(o) }foreachof your language is this pattern, built in: every source exposes the same way to move on by one element (in PHP, theIteratorinterface). - Observer: an object notifies a list of subscribers when it changes, without knowing them (detailed in idea 5):
A newsletter works the same: the sender does not know who subscribed, it sends, everyone reacts.// inside the mechanism: a list of subscribers + one loop, // that is THE WHOLE pattern class Subject { subscribers = [] subscribe(fn) { this.subscribers.push(fn) } notify(info) { for (fn of this.subscribers) fn(info) } } stock = new Subject() // the product page wants to know stock.subscribe(updateProductPage) // the customer alert too stock.subscribe(backInStockEmail) // both react; stock knows neither of them stock.notify('back in stock') - Mediator: objects stop talking to each other and all go through a central coordinator that decides what each one does. A control tower: planes don't talk to each other, they talk to the tower, which decides who lands. Unlike Observer, which simply notifies whoever listens, here the center decides. A shop case: the delivery slot form, where picking a date must reload the hours and disable "Confirm":
// without a mediator: every field knows every other one (n² // links, hell to change) // with one: fields only know the form: it orchestrates class Form { signal(what) { if (what === 'date') { timeField.reload() // slots follow the day submitButton.disable() // until a time is set } } } dateField.onChange = () => form.signal('date') // dateField has no idea timeField exists: only the // central switchboard knows
At a glance, what each one lets vary:
| Pattern | What varies | In the shop |
|---|---|---|
| Strategy | the algorithm | shipping fees |
| State | the behavior, by stage | an order's "Cancel" |
| Iterator | how you walk | array, SQL or CSV |
| Observer | who reacts | product page, e-mail |
| Mediator | who talks to whom | date and time of the slot |
You may have noticed: these five examples come from the same online shop, from the fee calculation to the delivery slot. That is deliberate, and that is the lesson: one real application naturally summons five patterns, each called in by its own problem (fees that vary, an order that changes stage, stock that notifies). Above all, never do the reverse: an "ultimate Cart class" stacking all five patterns to look serious. It is the drift the authors themselves distrust (idea 7). The book's case study, Lexi (idea 4), is the long version of this same lesson.
So the working question in front of your own code is never "which pattern can I use here?" but "what is going to change?". Find the axis of variation, wrap it in an object, and you usually rediscover one of the 23 without opening the book.
Not like a class bristling with patterns: like a small architecture where each one holds the exact post where it earns its keep. The skeleton:
// the cart itself: NO pattern. The most central class is
// the dumbest one.
class Cart {
add(product, qty)
total()
}
// STRATEGY: fees vary
interface ShippingFee {
compute(cart)
}
// DECORATOR: the promo stacks on any carrier
class FreeShippingOver implements ShippingFee {
__construct(base, threshold) { ... }
}
// STATE: life stages
class Order {
state
cancel() {
state.cancel()
}
}
// OBSERVER: paying notifies email and stock
class Events {
subscribe()
publish()
}
// FACADE: single entry point
class Checkout {
__construct(shipping, events) { ... }
placeOrder(cart) { ... }
}
// the assembly: every concrete choice happens at the root,
// never inside the classes
checkout = new Checkout(
// free shipping from 50 €
new FreeShippingOver(new StandardPost(), 50),
events)
Three things to notice. Each pattern answers a nameable problem (fees vary, the promo stacks, the order has stages, paying must notify email and stock without knowing them, the payment screen wants a single "Order" button). That single button is a Facade, seen in idea 6: a simple entrance in front of this whole little system. The central class has no pattern. And the absentees are a choice. No Singleton, that class allowed a single instance reachable from everywhere: the final assembly hands each class the parts it needs. No Command (an action stored in an object so it can be replayed or undone, idea 4): nobody asked to undo or replay. A good design shows in its absent patterns as much as its present ones.
The step-by-step version is built in the hands-on project "Build the shop, one pattern at a time" (in French), and the story of its design is on the blog.
4Lexi: eight patterns born from one document editor
Chapter 2 is the living heart of the book: the authors design Lexi, a WYSIWYG document editor ("what you see is what you get": the screen shows the final page directly, like Word), and each concrete problem gives birth to a pattern, in context. Strategy, Decorator and Iterator, already met in ideas 1 and 3, reappear here in one program.
- a document is text inside rows inside columns, recursively → Composite, the pattern that treats the single element and the group through the same interface (the book calls Glyph any element of a document, letter or page: you ask either one to "draw yourself").
- you want to be able to change the method that computes where lines break, including TeX's (Knuth's typesetting system, famous for its perfect line breaks), without touching the rest of the editor → Strategy (the object that computes the breaks is called the Compositor).
- add a border or a scrollbar without subclassing everything → Decorator, the wrapper that adds a responsibility to an object without modifying it, stackable (border around scrolling around page).
- support several look-and-feels (Motif, the one of 1990s Unix, and Presentation Manager, the one of OS/2) → Abstract Factory, the factory that produces a whole family of matching objects (buttons, menus, bars of the same theme) without the client knowing the concrete classes ("there's no longer anything in the code that mentions Motif by name", ch. 2). It picks the right objects for one look-and-feel.
- handle several window systems → Bridge, the bridge between what a window does (Window) and how a given window system draws it (WindowImp, Imp for implementation). Where Abstract Factory makes the right objects for a look-and-feel, Bridge separates the window from its drawing, system by system.
- menus, buttons and shortcuts trigger the same action, with undo → Command, the action turned into an object you can store, replay or undo (a history list with Execute/Unexecute: that is your Ctrl+Z).
- spell-check the whole document without adding a spelling method to every kind of element → Iterator (it moves from one element to the next) + Visitor (the operation applied to each one, kept outside the elements: here checking a word; tomorrow, counting words).
Read this chapter even if you skip the catalog (the entries that describe the patterns one by one): it shows patterns as answers to felt problems, not as shapes to impose.
5Observer, the pattern that ate the world
One object changes, and an open-ended set of others must follow, without the first knowing them. The book's example: a spreadsheet and a bar chart showing the same data object, each refreshing when the user edits the other, while "the spreadsheet and the bar chart don't know about each other". This mechanism is called Observer.
The subject keeps a list of subscribers and notifies them when it changes: that is the whole machine. You already write it every day without thinking. In button.addEventListener("click", myHandler), the button is the subject, your function is the subscriber, and the button knows nothing about it.
The consequence the book underlines: the coupling (how much one object depends on another) is "abstract and minimal". The subject only knows it has subscribers, nothing more. A low-level object, like the data, can therefore notify a high-level one, like the screen, without depending on it: the layers do not mix.
The book also names the trade-off. With push, the subject sends the details of the change, which forces it to guess what each subscriber wants: it is less reusable. With pull, it only says "I changed" and each subscriber fetches what it needs: sometimes that is wasted work.
You find the same pattern everywhere: an event listener, a pub/sub queue (senders post messages, subscribers receive them), a reactive state (a screen that redraws itself when its data changes). When you see an addEventListener or a subscription, you are looking at an Observer.
6Same silhouette, four intentions
Observer is recognized by its intent, not its shape, and that holds for every pattern. Adapter, Decorator, Proxy and Facade all look alike in a diagram: an object standing in front of one or more others. The book spends its end-of-chapter discussions separating them, because what names a pattern is not its shape, it is its intent:
| Pattern | Interface | Intent |
|---|---|---|
| Adapter | changes | makes two things fit that were never designed to, like a plug adapter ("makes things work after they're designed") |
| Decorator | the same | adds responsibilities, stackable at runtime |
| Proxy | the same | controls access: lazy-load the image, or count the references (know how many pieces of code still use an object) |
| Facade | new, simpler | one Compile() in front of the three steps of a compiler (scanner, parser, generator) |
The book pushes the distinction down to the closest pairs: a decorator changes the skin (it adds behavior around the object), a strategy changes the guts (it replaces how the object does its work). A MacroCommand is a Composite of Commands (idea 4), that is a command made of commands, like a macro recorder. Shared State objects "are essentially flyweights", those small objects everybody shares instead of copying. The order's states (idea 3) hold no data specific to one order: a single instance of each is enough for all. The Flyweight chapter works out the numbers on a document where every character is an object: 180,000 characters need only ~480 shared objects. What changes from one character to the next, the position and the font, is not stored in the object: it is supplied from outside, at drawing time. The patterns are not 23 bricks, they are 23 intentions that combine. Combining does not mean stacking everything: the book advises starting simple, that is the next idea.
7The one process tip: start simple, evolve when it hurts
The creational chapter, the patterns used to make objects (Abstract Factory, Builder, Factory Method, Prototype, Singleton), compares its five patterns on the same toy program: a maze game to build, with its rooms, walls and doors. It closes with the only real process advice in the book. A word first on the pattern it cites: Factory Method is a method that creates the object and that subclasses can redefine. In a Factory Method, the parent class calls your method, not the other way around. The book names this reversal, about another pattern (Template Method), the "Hollywood principle": "Don't call us, we'll call you". It is the inversion of control that frameworks rely on, those ready-made structures where your code plugs in. The advice: "often, designs start out using Factory Method and evolve toward the other creational patterns as the designer discovers where more flexibility is needed" (Creational discussion). Translation: don't install an Abstract Factory on day one. Subclass one creation method, and upgrade when reality asks. This does not contradict idea 2: it is the simplest starting point, and composition takes over when you need to vary more.
The same restraint closes chapter 1: "A design pattern should only be applied when the flexibility it affords is actually needed" (ch. 1). As early as page 31, the authors warned against pattern fever: the urge to apply them everywhere because you know them. Few readers made it to that sentence.
8The classic that apologizes for existing
The conclusion opens with a sentence no marketing department would allow: "It's possible to argue that this book hasn't accomplished much" (Conclusion). No new algorithms, no theory: "it just documents existing designs". They claim only one contribution, the one from idea 1, the vocabulary: naming what good programmers were already doing, so it could be taught and discussed.
And the humility is not a pose. The book took years to exist: it grew out of a thesis, then workshops. A first 90-page paper, judged too long for a conference, was replaced by a summary, which was accepted. Even the names changed along the way: Singleton was first called Solitaire, Visitor was Walker, and Facade used to be Glue. Renaming them was, by the authors' own admission, one of the hardest jobs, as idea 1 said. Their final admission: "finding patterns is much easier than describing them" (Conclusion). Anyone who has ever written docs knows that one is true.
My take, honestly
My verdict: read chapter 1 and Lexi like a book, consult the rest like a dictionary. Honest about my level first: I am a web developer, I do not spend my days quoting computer science books. The names, though, I have met them forever: Strategy and Singleton live in the Symfony docs, in job interviews, in conversations between devs. This book is where they come from, and I wanted to see the source.
Its strength is the vocabulary. I will not remember the 23 patterns, and neither will you: what stays are the names. A name compresses a whole conversation (idea 1): when I tell an AI assistant "extract this into a Strategy", it works on the first try. The two principles fit in two sentences (idea 2), and the question "what is going to change?" (idea 3) lets you rediscover a good part of the catalog without opening it. The prose half (chapter 1, the Lexi editor of idea 4, the conclusion of idea 8) is clear, humble, and full of warnings against the pattern fever (idea 7) the book launched itself.
First reservation, the dictionary half is dry: C++ from 1994 (the everyday object-oriented language back then), vanished technologies. My eyes slid off entire pages, and I own that. Consequence: this book is consulted, not read in one go.
Second reservation, part of the catalog has aged. Iterator lives inside every language's foreach, Observer inside reactive primitives, and saying "Singleton" in a job interview has become a risk sport. Consequence: it is up to you to sort what remains useful. Two gaps, which other books fill:
- the small safe steps to move from inheritance to composition (delegation): Refactoring.
- the interface and polymorphism as an architecture rule rather than a catalog: Clean Architecture.
My advice: read chapter 1 (ideas 1 and 2) and Lexi (idea 4) like a book, and keep the rest as a dictionary you consult when needed. If you only read one of the two, pick HFDP, the illustrated textbook: it is built for learning. This one is the stern grandfather you visit to check the source.
Odilon
Still relevant in 2026?
Yes for the vocabulary, less for the code. The vocabulary is more alive than the book: it is the shared API between developers, interviews, frameworks docs, and now AI assistants, which were trained on thirty years of text written in GoF.
What has aged: the C++ and Smalltalk code (an older, purely object-oriented language), the class-heavy style, and the patterns languages have absorbed (see my second reservation). Functional composition solves some of these problems with less ceremony. The two principles (idea 2) and the intent-based reading (idea 6) have not moved an inch.
Who is it for?
Read it if
- You use the words Factory, Observer or Singleton daily and want to drink at the source
- You design OO code (PHP, Java, C#, TypeScript) and inheritance keeps hurting you
- You read Head First Design Patterns and want the precise, complete reference
- You review AI-generated code: naming the structure is the fastest feedback there is
Skip it if
- You expect a page-turner: half of it is a reference to consult, in 1994 C++
- You live in functional or procedural code: composition of functions replaces half the catalog
- You are starting OOP: begin with Head First Design Patterns, come back here later
Going further
- My PHP OOP course: patterns practiced in PHP, exercise by exercise.
- Head First Design Patterns: the same catalog retold with jokes and quizzes, built for learning.
- PHP 8 Objects & Patterns: the catalog applied to PHP.
- Clean Architecture: its Dependency Rule rests on the same polymorphism (one interface, several interchangeable implementations).
- Refactoring: the safe steps to move toward a pattern, or away from it.
Comments (0)