Design Patterns: Origin, Why They Matter, the Three Families
"A pattern language guides a designer by providing workable solutions to all of the problems known to arise in the course of design." — Kent Beck and Ward Cunningham, Using Pattern Languages for Object-Oriented Programs, OOPSLA-87 workshop, 17 September 1987
Summary: A design pattern is a named, documented solution to a problem that keeps coming back, written down with its trade-offs so a team can discuss it in one word. It is a vocabulary and a set of consequences, not a library and not a goal. Focus: Alexander's pattern language, the Hillside/PLoP community, the GoF book and its 23 patterns by family, the description template, what patterns are not, idioms vs patterns vs principles, smells and refactoring to patterns, Norvig's critique and "pattern-itis", how to choose a pattern, and which patterns Go and PHP make trivial, with Laravel and Go standard library examples. Learning goal: Open any pattern description, say which problem it answers and what it costs, decide whether your language already gives you a simpler tool, and recognise the pattern when you meet it in Laravel or in the Go standard library.
This page is the map for the whole design patterns group. It tells the story (Alexander, Beck and Cunningham, the GoF book), lists all 23 GoF patterns once with a link to the chapter that teaches each, explains the template every pattern description follows, and says honestly where patterns help and where they hurt. It does not teach the patterns themselves: those live in Creational, Structural and Behavioral patterns, and choosing and combining them is the job of Patterns in practice. The principles behind them are on SOLID, the problems that call for them on Code smells and refactoring, and the vocabulary of classes and polymorphism on OOP modeling fundamentals.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in a few tables | Everything in one minute |
| Why patterns exist and what they trade | Why patterns exist |
| Alexander, Beck and Cunningham, GoF, PLoP, Norvig | Where it comes from |
| The 23 GoF patterns by family with intent and chapter links | The 23 patterns in one table |
| Name, intent, motivation, structure, consequences | The pattern template |
| What patterns are not (library, goal, recipe) | What patterns are not |
| Creational, structural, behavioral and the families beyond GoF | The families |
| Idiom vs pattern vs principle vs architecture | Patterns, idioms and principles |
| Smells, Refactoring to Patterns | Patterns and code smells |
| Norvig, "missing language feature", pattern-itis | Criticism |
| Which patterns are trivial in Go or PHP | Modern relevance in Go and PHP |
| Where each pattern already hides in Laravel and Go | Where patterns already live |
| One pattern per family in Go and Laravel | Go, Laravel |
| How to pick a pattern | Choosing |
| Monolith to distributed systems | In architecture |
| Hands-on grep and run exercises | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked later.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Pattern | A named solution to a recurring problem in a context, with its trade-offs | "Strategy": swap the discount rule | Every team re-invents the idea and calls it something else |
| Pattern language | Patterns that reference each other in an order | Beck and Cunningham's five Smalltalk window patterns | A bag of unrelated tricks |
| Catalogue | A book or site listing patterns in one template | GoF, PoEAA, EIP | Patterns are folklore, not reference |
| Idiom | A language-specific way to write something small | Go functional options | Confused with a design-level decision |
| Principle | A rule of thumb that judges designs | Single Responsibility | Patterns applied without a reason |
| Smell | A symptom in code that suggests a design problem | Long switch on type | You add a pattern where nothing hurts |
| Pattern-itis | Using patterns because they exist, not because a problem exists | AbstractUserFactoryProvider | Code nobody can follow |
The three GoF families and the question each answers.
| Family | Count | Question it answers | Typical example |
|---|---|---|---|
| Creational | 5 | How do I make objects without hard-wiring the concrete class? | Factory Method |
| Structural | 7 | How do I assemble objects into bigger structures? | Decorator |
| Behavioral | 11 | Who does what, and how do objects talk? | Strategy |
Beyond GoF.
| Family | Scale | Where it is taught |
|---|---|---|
| Concurrency patterns | Threads, goroutines, queues | Designing for concurrency |
| Enterprise application patterns (Fowler, PoEAA) | Persistence and domain logic of one application | Data persistence in design |
| Architectural patterns | Whole system | Styles vs patterns |
| Messaging and integration patterns (Hohpe and Woolf, EIP) | Between processes | Messaging fundamentals |
Where patterns live in your tools.
| Level | Go | Laravel |
|---|---|---|
| Creation | NewX functions, registries like database/sql | Service container bindings |
| Wrapping | io.Reader wrappers, http.Handler middleware | Cache decorators, middleware, Pipeline |
| Behaviour swap | sort.Interface, function types | Cache and queue drivers, closures |
| Notification | Channels, callbacks | Events and listeners, Eloquent observers |
| Persistence | database/sql plus your repository | Eloquent (Active Record), query builder |
Why patterns exist
Designers meet the same problems again and again: how to create objects without knowing their class, how to add behaviour without editing old code, how to tell several parts of a program that something happened. Experienced people solve them with a handful of shapes. A pattern writes that shape down together with when it fits, what it costs and what it is called. The name is the biggest part of the value: "put a Decorator around it" is a whole design conversation in four words.
| Without a shared vocabulary | With a catalogue of patterns |
|---|---|
| Every design discussion starts from objects and arrows | Start from "this is a Strategy, with these consequences" |
| New hires learn by reading the whole codebase | New hires recognise shapes they have seen in other systems |
| A trade-off is discovered in production | The known consequences are listed before you build |
| Reviews argue about taste | Reviews argue about which problem is being solved |
| Cost: you must learn the names | Cost: names can hide the simple solution, and can be over-applied |
The analogy we reuse on this page: a cookbook for sauces. A French kitchen does not invent béchamel every evening; "béchamel" is a name for a known recipe with known variants (add cheese, get Mornay) and known failure modes (it forms lumps if you add milk too fast). The recipe is not a bottle of sauce you open: you still cook it, in your pan, with your ingredients. A pattern is that recipe. And nobody serves béchamel on every plate just because they know how.
Three common misunderstandings, up front
- "Patterns are code you can copy." They are descriptions of a shape. The same pattern looks different in Go, PHP and Java. Copying the book's UML into Go usually produces worse code than the idea would.
- "More patterns means a better design." Patterns cost indirection. A design with five patterns where none of them solves a problem you have is worse than a plain one.
- "Patterns are Java, from the 1990s, and Go and PHP do not need them." The names are old; the problems are not. Go's
http.Handlerchain is Decorator. Laravel's container is a factory. You use patterns every day; the question is whether you recognise them.
Where it comes from
Alexander, 1977. The idea of a pattern in design comes from architecture, not software. Christopher Alexander, Sara Ishikawa, Murray Silverstein and colleagues of the Center for Environmental Structure in Berkeley published A Pattern Language: Towns, Buildings, Construction (Oxford University Press, 1977): 253 patterns that run from regions and cities down to rooms and doorknobs. Each is a problem, a solution and links to larger and smaller patterns. The authors treat them as hypotheses:
"the patterns are still hypotheses, all 253 of them—and are, therefore, all tentative, all free to evolve under the impact of new experience and observation." — Alexander et al., A Pattern Language, p. xv (as quoted on Wikipedia, which is a secondary source; we did not read the book)
Two ideas from Alexander matter for software. A pattern is empirical (it is "our current best guess"), and patterns form a language: each one is used inside bigger ones and contains smaller ones.
Beck and Cunningham, 1987. Kent Beck (Apple) and Ward Cunningham (Tektronix) wrote a technical report for an OOPSLA-87 workshop that moved the idea to programming. They proposed five patterns for Smalltalk windows (Window Per Task, Few Panes Per Window, Standard Panes, Short Menus, Nouns and Verbs) and report that a team of application specialists "were able to specify very reasonable interfaces after one day of practice" without knowing Smalltalk's interface mechanisms. Their description of a pattern is still the best short one: "a statement of a problem, a summary of circumstances creating the problem and, most important, a solution that works in those circumstances."
GoF, 1994. Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, "the Gang of Four", published Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, first published on 21 October 1994 with a 1995 copyright). According to Wikipedia, the book began at a birds-of-a-feather session at OOPSLA 1990 where Gamma and Helm met; the first two chapters discuss object-oriented design and the rest describe 23 patterns. Two sentences from chapter 1 became slogans: "Program to an interface, not an implementation." and "Favor 'object composition' over 'class inheritance'." The authors also warn: "Dynamic, highly parameterized software is harder to understand and build than more static software." (all quoted via Wikipedia's summary of the book, citing GoF 1995:18, 20, 21.)
Hillside and PLoP, 1994 onward. The Hillside Group runs the Pattern Languages of Programs (PLoP) conferences and states that it "promotes the use of patterns and pattern languages to record, analyze, and share knowledge". Wikipedia dates the first PLoP conference to 1994 and the Portland Pattern Repository (the site that became the first wiki) to the following year. PLoP papers go through "shepherding" and writers' workshops, which is why pattern literature has a recognisable review culture. The Pattern Languages of Program Design books (Coplien and Schmidt, 1995 onward) collect PLoP papers.
Fowler, 2003. Martin Fowler's catalogue of Patterns of Enterprise Application Architecture (page dated 5 March 2003) is the model for patterns above the class level: "layering, structuring business logic, structuring a web user interface, linking in-memory data to a relational database, and handling session state in stateless environments."
Norvig, 1996/1998. Peter Norvig's talk at Object World (5 May 1996) argued that "16 of 23 patterns have qualitatively simpler implementation in Lisp or Dylan than in C++ for at least some uses of each pattern". Section Criticism uses it.
Kerievsky, 2004. Joshua Kerievsky's Refactoring to Patterns (Addison-Wesley, August 2004) says that "using patterns to improve an existing design is better than using patterns early in a new design". Section Patterns and code smells uses it.
Year Who What
1 1977 Alexander et al. A Pattern Language: 253 patterns for towns and buildings
2 1987 Beck, Cunningham Pattern languages for Smalltalk windows (OOPSLA-87)
3 1994 Gamma, Helm, Johnson, Vlissides Design Patterns: 23 patterns; first PLoP conference
4 1996 Norvig 16 of 23 patterns simpler in Lisp/Dylan
5 2003 Fowler PoEAA catalogue (enterprise patterns)
6 2004 Kerievsky Refactoring to PatternsThe 23 patterns in one table
The table is the complete GoF list. Intents are written in our words (we did not re-read the book; the pattern names and family split match the refactoring.guru catalogue and Wikipedia's summary, with one difference: that site lists 22 patterns and leaves out Interpreter). The links go to the chapter that teaches each pattern.
| Pattern | Family | One-line intent | Chapter |
|---|---|---|---|
| Singleton | Creational | Exactly one instance, with a global access point | Singleton |
| Factory Method | Creational | Let a method decide which concrete class to create | Factory Method |
| Abstract Factory | Creational | Create families of related objects without naming concrete classes | Abstract Factory |
| Builder | Creational | Build a complex object step by step | Builder |
| Prototype | Creational | Create new objects by copying an existing one | Prototype |
| Adapter | Structural | Make one interface look like another | Adapter |
| Bridge | Structural | Separate an abstraction from its implementation so both vary | Bridge |
| Composite | Structural | Treat a tree of objects and a single object the same way | Composite |
| Decorator | Structural | Add behaviour by wrapping an object with the same interface | Decorator |
| Facade | Structural | One simple entry point to a complex subsystem | Facade |
| Flyweight | Structural | Share small immutable objects to save memory | Flyweight |
| Proxy | Structural | A stand-in that controls access to another object | Proxy |
| Chain of Responsibility | Behavioral | Pass a request along handlers until one handles it | Chain of Responsibility |
| Command | Behavioral | Turn a request into an object you can queue, log and undo | Command |
| Interpreter | Behavioral | Represent a small grammar and evaluate sentences of it | Behavioral patterns |
| Iterator | Behavioral | Walk a collection without exposing its structure | Iterator |
| Mediator | Behavioral | Let objects talk through one coordinator instead of each other | Mediator |
| Memento | Behavioral | Capture and restore an object's state without breaking encapsulation | Memento |
| Observer | Behavioral | Notify dependants when something changes | Observer |
| State | Behavioral | Change behaviour when the internal state changes | State |
| Strategy | Behavioral | Make an algorithm interchangeable at runtime | Strategy |
| Template Method | Behavioral | Fix the skeleton of an algorithm, let steps vary | Template Method |
| Visitor | Behavioral | Add operations to a class hierarchy without editing the classes | Visitor |
The creational chapter also teaches Simple Factory, which is not one of the 23: it is a common idiom that the owner of this path chose to include because it is the version most code actually uses.
The pattern template
A catalogue is useful because every pattern is described with the same sections, so you can compare them. Norvig's slides, quoting the GoF book and the PLoP books, list what is in a pattern: Pattern Name, Intent, Also Known As, Motivation, Applicability, Structure, Participants, Collaborations, Consequences, Implementation, Sample Code, Known Uses, Related Patterns. Refactoring.guru shortens it to Intent, Motivation, Structure and Code example, adding Applicability, implementation steps and relations "in some catalogs".
| Section | Question it answers | Example, for Decorator |
|---|---|---|
| Name | What do we call it in a code review? | Decorator (also known as Wrapper) |
| Intent | What problem does it solve, in one sentence? | Add behaviour to an object without changing its class |
| Motivation | A concrete scenario where the problem hurts | Logging, caching and auth around one handler |
| Applicability | When should I reach for it, when not? | Several optional behaviours that combine in any order |
| Structure | What are the classes and arrows? | Component, ConcreteComponent, Decorator holding a Component |
| Participants | What role does each class play? | Component is the interface, decorators implement it too |
| Collaborations | Who calls whom at runtime? | The decorator forwards to the wrapped component |
| Consequences | What do I gain and pay? | Flexible, but many small objects and a hard-to-read stack trace |
| Implementation | Hints and traps | Keep the interface small, or wrappers must forward everything |
| Known uses | Where does it already exist? | io.Reader wrappers, http.Handler middleware |
| Related patterns | What is nearby? | Proxy has the same shape but a different intent |
Pattern description is a contract Must-know
In plain words: a pattern page is a small decision document: here is the problem, here is the move, here is the bill.
Common misunderstanding: "The class diagram is the pattern." The diagram is the structure section only. Two patterns can have the same diagram (Strategy and State, Decorator and Proxy) and differ in intent and consequences. Read Intent first, Consequences last, and treat Structure as an example.
Definition: a pattern is a named abstraction of a solution, specified by problem, context, forces, solution and consequences, with enough generality to be reimplemented in different programs.
Reading order for an unfamiliar pattern
1 Name and Intent -> do I know this problem?
2 Motivation -> do I have this scenario?
3 Applicability -> and not the opposite one?
4 Consequences -> can I afford the bill?
5 Structure, Participants -> only now, the shape
6 Known uses -> where do I see it in real code?Real scenarios: a code review comment "this should be a Strategy" is only useful if both people mean the same Intent; an ADR that says "we chose a Decorator for caching because the repository interface is stable" lists consequences; a new hire opens http.Handler and sees the Decorator from Known uses.
What patterns are not
Not a library, not a framework Must-know
In plain words: you cannot import a pattern. You write it, in your language, for your problem.
Common misunderstanding: "If Strategy is useful there must be a Strategy package." Refactoring.guru: "You can't just find a pattern and copy it into your program, the way you can with off-the-shelf functions or libraries. The pattern is not a specific piece of code, but a general concept for solving a particular problem."
| Thing | You get | You must write |
|---|---|---|
Library function (sort.Slice) | Working code, tested | A call |
| Framework (Laravel) | A skeleton that calls your code | Your hooks |
| Pattern (Strategy) | A name, an intent, consequences | The code, fitted to your types |
| Algorithm (quicksort) | Precise steps | Their implementation |
Refactoring.guru uses the same contrast: an algorithm is a cooking recipe with clear steps; a pattern is "more like a blueprint: you can see what the result and its features are, but the exact order of implementation is up to you."
Not a goal Must-know
In plain words: the goal is code that is easy to change. A pattern is one possible route, never the destination.
Common misunderstanding: "A good design uses many patterns." A design with one clear Strategy where a rule really varies is good; a design with eight patterns and no varying rule is a maze. Kerievsky's position is a good test: improve an existing design with patterns when the code hurts, instead of building patterns up front.
| Healthy reason | Unhealthy reason |
|---|---|
| "The discount rule changes every quarter" | "We might need to swap the database one day" |
"Three branches of this switch grow together" | "The book says use Abstract Factory here" |
| "We have two implementations today" | "A senior engineer likes it" |
Not a recipe with one right form Important
Each language bends the pattern: the same Observer is a class with attach/notify in Java, a slice of callbacks in Go and an Event::listen call in Laravel. A pattern that is copied to the letter, "without adapting them to the context of their project", is one of the three criticisms refactoring.guru lists (the others are kludges for weak languages and unjustified use).
The families
Creational, structural, behavioral Must-know
In plain words: creational patterns are about making objects, structural about assembling them, behavioral about who does the work and how they talk.
Common misunderstanding: "The families are strict boxes." They are a teaching aid. Decorator (structural) and Chain of Responsibility (behavioral) are the same wrapping idea; Strategy and State differ only in who changes the strategy and why. Choose by the problem, not the family.
| Family | Refactoring.guru's one-line definition | Patterns |
|---|---|---|
| Creational | "various object creation mechanisms, which increase flexibility and reuse of existing code" | Singleton, Factory Method, Abstract Factory, Builder, Prototype |
| Structural | "how to assemble objects and classes into larger structures while keeping these structures flexible and efficient" | Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy |
| Behavioral | "concerned with algorithms and the assignment of responsibilities between objects" | Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor |
One request, three families
1 Caller asks "give me a Notifier" -> Factory Method (creational)
2 The Notifier is wrapped with retry -> Decorator (structural)
3 Retry policy is chosen per customer -> Strategy (behavioral)
4 A failure is announced to listeners -> Observer (behavioral)Families beyond GoF Important
In plain words: "design pattern" without a qualifier usually means GoF, but the word is used at every scale.
Common misunderstanding: "Repository, Saga and Outbox are GoF patterns." They are not. They come from other catalogues with other scales; calling them GoF makes people look for a class diagram that does not exist.
| Family | Catalogue | Examples | Scale | Taught in |
|---|---|---|---|---|
| Concurrency | Schmidt et al., POSA 2; Go blog on pipelines | Worker pool, pipeline, fan-out/fan-in, actor | One process, many threads or goroutines | Concurrency design |
| Enterprise application | Fowler, PoEAA (2003 page) | Active Record, Data Mapper, Repository, Unit of Work, Identity Map, Lazy Load, Service Layer, Front Controller, DTO | One application and its database | Data persistence, Repositories |
| Architectural | Buschmann et al. POSA 1; Bass, Clements, Kazman | Layers, pipe-and-filter, microkernel, hexagonal | Whole system | Styles vs patterns, Layered monolith |
| Messaging and integration | Hohpe and Woolf, EIP | Message Channel, Content-Based Router, Translator, Outbox, Saga, Dead Letter Channel | Between processes | Messaging fundamentals, Outbox, Saga, Dead-letter queue |
| Presentation | Fowler PoEAA; Smalltalk MVC | MVC, Page Controller, Front Controller, Template View | UI layer | MVC, MVP, MVVM |
| Domain-driven design | Evans, 2003 | Aggregate, Factory, Repository, Domain Event | One bounded context | Aggregates and factories |
| Organisational and process | Coplien; the Hillside collection | Patterns for teams and processes | People | Hillside library |
Fowler's own catalogue page shows the point: its groups are Domain Logic, Data Source Architectural, Object-Relational (behavioral, structural, metadata mapping), Web Presentation, Distribution, Offline Concurrency, Session State and Base patterns. Active Record there is "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data." That is not a GoF pattern, yet you use it every time you call $order->save() in Laravel.
Patterns, idioms and principles
Pattern vs idiom Important
In plain words: an idiom is how people say a small thing in one language; a pattern is how people solve a design problem in any language.
Common misunderstanding: "Functional options is a pattern." It is a Go idiom. Rob Pike introduced it (2014 blog post) to solve "setting options in a Go package": "an option is implemented as a function we call to set the state of that option." The problem (many optional settings) is a Builder-like problem; the Go way to say it is an idiom that exists because Go has no default arguments or overloading.
| Question | Pattern | Idiom |
|---|---|---|
| Scope | Several types and their relations | One construct or a few lines |
| Language | Mostly language-independent | Specific to one language |
| Example in Go | Decorator, Strategy | Functional options, defer to unlock, errors.Is, return error last |
| Example in PHP | Observer, Chain | Constructor promotion, readonly, enum with match, named arguments |
| Where documented | Catalogues (GoF, PoEAA) | Language guides (Effective Go, PHP manual) |
| Failure when ignored | Reinvented design, naming drift | Code that fights the language |
Effective Go gives the Go mood: "Interfaces with only one or two methods are common in Go code". Small interfaces and implicit satisfaction make several patterns nearly disappear (see relevance).
Same need, three levels
1 Need: build a Server with 12 optional settings
2 Pattern: Builder (a Builder class, setters, Build())
3 Java idiom: fluent builder, immutable result
4 Go idiom: NewServer(addr, WithTLS(), WithTimeout(5*time.Second))
5 PHP idiom: new Server(addr: ':8080', tls: true) // named argumentsPattern vs principle Important
In plain words: a principle tells you whether a design is good; a pattern is one design you can choose.
Common misunderstanding: "SOLID and patterns are the same kind of thing." Principles are tests applied to any code ("does this have one reason to change?"); patterns are shapes (Strategy, Decorator). Many patterns are what you get when you apply a principle to a specific problem.
| Principle | Pattern that often follows from it |
|---|---|
| Single Responsibility | Facade (one entry per actor), Command (one use case per class) |
| Open–Closed | Strategy, Decorator, Template Method, Observer |
| Liskov Substitution | Constrains every pattern that relies on subtypes (State, Strategy) |
| Interface Segregation | Adapter, role interfaces, Facade |
| Dependency Inversion | Factory Method, Abstract Factory, dependency injection |
| GoF chapter 1: program to an interface | Almost all of them |
| GoF chapter 1: composition over inheritance | Strategy, Decorator, Bridge, State |
For the quality words behind this (coupling, cohesion, information hiding) see Design quality principles.
Patterns and code smells
Smell first, pattern second Must-know
In plain words: a smell is the pain you can see in the code; a pattern is one of the cures. Start from the pain.
Common misunderstanding: "Learn the patterns, then look for places to use them." This produces pattern-itis. Kerievsky's Refactoring to Patterns suggests the opposite order: write the simple code, let the smell appear, then refactor toward the pattern through small steps.
| Smell (see Code smells) | Pattern it often points to | Move |
|---|---|---|
| Switch statements on a type code | Strategy, State, polymorphism | Replace Conditional with Polymorphism |
| Long Method with several phases | Template Method, Strategy | Extract Method, then lift to a hook |
| Divergent Change | Facade plus separate modules | Extract Class |
| Shotgun Surgery | Move behaviour to one place (Observer, Mediator) | Move Method |
| Feature Envy | Move the method to the data's class | Move Method |
| Duplicate Code across subclasses | Template Method | Pull Up Method |
| Primitive Obsession | Value Object, State | Replace Data Value with Object |
| Speculative Generality | Remove the pattern | Inline Class, Collapse Hierarchy |
| Long Parameter List / telescoping constructors | Builder, functional options | Introduce Parameter Object |
Object creation scattered with new and branches | Factory Method | Replace Constructor with Factory Method |
| Hard-coded dependency on a concrete class | Dependency injection | Extract Interface |
Notice the eighth row: sometimes the right move is to remove a pattern. Speculative Generality (a smell on refactoring.guru's list) is a pattern applied before the problem existed.
Refactoring to a pattern, as a timeline
1 Week 1 discount is one if/else in Checkout.pay() (no pattern, correct)
2 Week 5 finance adds a second rule, third branch appears (smell: Switch Statements)
3 Week 6 Extract Method, then Extract Interface Discount
4 Week 7 each branch becomes a type (Strategy), Checkout depends on the interface
5 Week 20 marketing adds seasonal rules: add a type, edit nothing elseCriticism
Patterns as missing language features Important
In plain words: if your language cannot say something directly, you invent a convention for it and give the convention a name. The name is a pattern. When the language adds the feature, the pattern disappears.
Common misunderstanding: "Norvig proved patterns are useless." He showed that many GoF patterns are simpler or invisible in a dynamic language with first-class functions and types, and he kept the idea of patterns ("Descriptions of what experienced designers know (that isn't written down in the Language Manual)"). His grouping of the 16 patterns by the language feature that simplifies them:
| Language feature | GoF patterns that become invisible or simpler (Norvig, 1996) |
|---|---|
| First-class types (6) | Abstract Factory, Flyweight, Factory Method, State, Proxy, Chain of Responsibility |
| First-class functions (4) | Command, Strategy, Template Method, Visitor |
| Macros (2) | Interpreter, Iterator |
| Method combination (2) | Mediator, Observer |
| Multimethods (1) | Builder |
| Modules (1) | Facade |
He also gives three levels of implementation: Invisible ("So much a part of language that you don't notice"), Informal ("Design pattern in prose; refer to by name, but must be implemented from scratch for each use") and Formal ("Implement pattern itself within the language"). Paul Graham made a similar point in "Revenge of the Nerds" (we cite it through Wikipedia and refactoring.guru; not read). Hannemann and Kiczales (2002), also via Wikipedia, found that aspect-oriented programming removed code-level dependencies from 17 of the 23 patterns.
Go and PHP sit in between: Go has first-class functions and implicit interfaces but no inheritance and no macros; PHP has closures, first-class callable syntax, enums and magic methods but a class-based object model close to Java's. See the per-pattern table.
Over-engineering and pattern-itis Important
In plain words: pattern-itis is applying a pattern because you know it, not because the code asked.
Common misunderstanding: "The cure is to avoid patterns." The cure is to demand a problem first. Refactoring.guru's third criticism: "If all you have is a hammer, everything looks like a nail." The GoF authors themselves say flexibility has a price: "Dynamic, highly parameterized software is harder to understand and build than more static software."
| Symptom | Example | Cost | Fix |
|---|---|---|---|
| Interface with one implementation, never swapped | UserRepositoryInterface plus UserRepository for a single database | Two files for one idea; jump-to-definition lands on the interface | Delete the interface until a second implementation or a test needs it |
| Factory of factories | AbstractNotifierFactoryProvider | Names longer than the logic | Use a plain constructor |
| Singleton for convenience | Global Config::getInstance() | Hidden dependency, hard tests | Pass it in; let the container own lifetime |
| Strategy for one rule | Class StandardDiscount with an interface | Indirection with no variation | A function |
| Visitor on a hierarchy that changes weekly | Adding a class edits every visitor | Rigidity | Use a switch or polymorphism |
| Patterns as a hiring or review checklist | "Where is your Factory?" | Pattern count becomes the metric | Review for problem and consequences |
Over-engineered path vs plain path for "email a receipt"
1 Plain SendReceipt(order) calls mailer.Send(...) 1 file, 12 lines
2 Pattern-itis ReceiptSenderFactory -> ReceiptSenderStrategy -> EmailReceiptSender -> ReceiptEventObserver 5 files
3 When it pays off: second channel (SMS) arrives, or a test needs a fake -> extract the interface thenModern relevance in Go and PHP
Which patterns survive Must-know
In plain words: all 23 problems still exist. What changed is how much code the solution needs.
Common misunderstanding: "If Go has no classes, GoF is irrelevant." Go has interfaces, composition and embedding, which are exactly what GoF chapter 1 recommends. What disappears is ceremony, not the idea.
Verdicts: Trivial (one language feature does it), Idiom (a standard shape, small), Still useful (you will write it), Rare (needs a special situation).
| Pattern | Go | PHP (8.4) | Verdict |
|---|---|---|---|
| Singleton | Package-level variable or sync.Once; no class needed | $this->app->singleton(...) in the container; a static getInstance is a smell | Trivial in both; avoid hand-made |
| Factory Method | NewX(...) function, registry like sql.Register | Container binding closure, static named constructor | Trivial, still everywhere |
| Abstract Factory | A struct of constructor functions or one interface | Manager classes that return a driver family | Rare |
| Builder | Functional options or a struct literal | Named arguments; the query builder is a real fluent builder | Idiom in Go, Trivial in PHP for small objects |
| Prototype | Assignment copies a struct by value | clone keyword | Trivial |
| Adapter | A small wrapper struct; http.HandlerFunc adapts a function to Handler | A class implementing a contract and wrapping a vendor SDK | Still useful (anti-corruption) |
| Bridge | An interface field in a struct | Constructor-injected interface | Rare as a named pattern; used without a name |
| Composite | A struct holding a slice of the same interface | Same; Laravel collections, nested form components | Still useful for trees |
| Decorator | Wrap an interface; io.Reader, middleware | Wrap a contract; cache and logging decorators | Still useful, central |
| Facade | The package's exported API | A service class (not Laravel's static facades) | Trivial in Go, still useful in PHP |
| Flyweight | Share immutable values and intern strings by hand | Share immutable value objects | Rare |
| Proxy | Wrapper types, generated clients (gRPC) | Laravel facades, lazy objects, generated proxies | Still useful |
| Chain of Responsibility | http.Handler middleware | Middleware, Pipeline | Still useful, central |
| Command | A function value or a struct with Run | Jobs, Artisan commands, form actions | Idiom in Go, Still useful in PHP (queued jobs) |
| Interpreter | Rare: parse and evaluate for DSLs | Rare: Blade, validation rule strings are mini-languages | Rare |
| Iterator | range; since Go 1.23 the iter package and range-over-func | foreach, Iterator, generators with yield, LazyCollection | Trivial in both |
| Mediator | Channels and select, an event bus | Events, command bus | Still useful |
| Memento | Copy the struct, snapshot to a byte slice | Serialisation, event-sourcing snapshots | Rare, but undo and snapshots need it |
| Observer | Callbacks, channels | Events and listeners, Eloquent observers | Idiom in Go, Trivial in Laravel |
| State | A state function, or a type with switch | Backed enum plus match, or state classes | Still useful, often an enum |
| Strategy | A function type or a small interface (sort.Interface) | Closures, contracts, drivers | Trivial in both: pass a function |
| Template Method | No inheritance: pass funcs or use an interface; sort.Sort | Abstract base class, Laravel handle() hooks | Idiom in Go, still useful in PHP |
| Visitor | switch v := x.(type) | match on instanceof, double dispatch only for stable hierarchies | Trivial in Go, Rare in PHP |
The Go 1.23 release notes confirm the Iterator row: "The new iter package provides the basic definitions for working with user-defined iterators", and the slices package gains functions such as All, Values, Backward, Collect and Sorted. PHP generators are described in the PHP manual (language.generators). Reading the verdict column as a whole: the creational patterns and Visitor, Strategy and Iterator shrink the most, while Adapter, Decorator, Chain of Responsibility, State, Mediator and Proxy keep their full weight, so most day-to-day work is in the wrapping and notification patterns.
Where patterns already live
Laravel Must-know
In plain words: Laravel is a pattern catalogue you can composer require. When you use its features you are using the patterns, even if you never named them.
Common misunderstanding: "Laravel facades are the Facade pattern." The GoF Facade is a simplified interface to a subsystem. Laravel's docs say facades "provide a 'static' interface to classes that are available in the application's service container", and the framework source implements this with __callStatic on Illuminate\Support\Facades\Facade, resolving an object and forwarding the call. That is closer to Proxy plus Service Locator. (The mapping is our classification from reading the source; the Laravel docs do not name the pattern.)
| Laravel feature | Pattern | Evidence (source read) |
|---|---|---|
Service container (bind, singleton, contextual binding) | Factory Method plus Dependency Injection; Singleton lifetime | Laravel docs: "Dependency injection is a fancy phrase that essentially means this: class dependencies are 'injected' into the class via the constructor" |
Facades (Cache::get) | Proxy to a container object (Service Locator flavour) | Facade::__callStatic and getFacadeRoot() in Illuminate/Support/Facades/Facade.php |
Pipeline facade, Illuminate\Pipeline\Pipeline | Chain of Responsibility | send(), through(), then() builds the chain with array_reduce in Pipeline.php |
| HTTP middleware | Chain of Responsibility, Decorator-shaped | Docs: "a series of 'layers' HTTP requests must pass through" |
| Events and listeners | Observer | Docs: "Laravel's events provide a simple observer pattern implementation" |
| Eloquent models | Active Record (PoEAA) | Docs: each table "has a corresponding 'Model' that is used to interact with that table"; matches Fowler's definition |
Query builder (DB::table()->where()) | Fluent Builder | Docs: "convenient, fluent interface to creating and running database queries" |
Cache, Queue, Mail, Filesystem drivers with CacheManager | Strategy chosen by a factory (the Manager) | Manager::driver(), createDriver() with customCreators for Cache::extend |
Macroable (Collection::macro) | Open class / extension object, "decorator-ish" at best | Macroable::macro() and __call() store closures and call them on the instance; it adds methods to a class, it does not wrap an instance, so it is not GoF Decorator |
Jobs (ShouldQueue) | Command | The job object carries a request to be run later |
Collections (map, filter) | Iterator plus fluent pipeline | Docs: collections are "macroable" |
Go standard library Must-know
In plain words: the standard library is small and almost every package is one pattern done in the Go way.
Common misunderstanding: "Go does not use patterns, it just uses interfaces." Interfaces are the mechanism; the shapes you build with them are the patterns.
| Standard library | Pattern | What to read |
|---|---|---|
io.LimitReader, io.TeeReader, io.MultiReader, io.NopCloser | Decorator and Adapter around io.Reader | pkg.go.dev/io: "TeeReader returns a Reader that writes to w what it reads from r." |
http.Handler, http.HandlerFunc, http.StripPrefix, http.TimeoutHandler | Adapter (func to interface), Decorator chain | pkg.go.dev/net/http: StripPrefix(prefix string, h Handler) Handler |
sort.Interface (Len, Less, Swap), sort.Reverse | Strategy (ordering) inside a fixed algorithm (Template Method flavour); Reverse is a decorator | pkg.go.dev/sort |
context.Context with WithCancel, WithValue | A chain of wrapped parents | pkg.go.dev/context: "A Context carries a deadline, a cancellation signal, and other values across API boundaries." |
database/sql Register and Open | Factory registry | Drivers register in init() |
| Functional options (many third-party packages, not the stdlib) | Idiom replacing Builder | Pike's 2014 post |
Go
One pattern per family. Each is complete and runs with go run.
Creational: Factory Method with a registry Must-know
The caller asks for a kind, never for a type. Adding a new notifier means registering a constructor; New does not change. This is how database/sql finds drivers.
// Creational family: Factory Method in Go is a constructor function plus a registry.
// database/sql does the same with sql.Register and sql.Open.
package main
import (
"fmt"
"sort"
)
// Notifier is the product interface: callers never see a concrete type.
type Notifier interface {
Notify(to, text string) string
}
type emailNotifier struct{ from string }
func (n emailNotifier) Notify(to, text string) string {
return fmt.Sprintf("email %s -> %s: %s", n.from, to, text)
}
type smsNotifier struct{}
func (smsNotifier) Notify(to, text string) string {
return fmt.Sprintf("sms -> %s: %s", to, text)
}
// registry maps a name to a constructor (the "factory method").
var registry = map[string]func() Notifier{}
// Register adds a constructor; packages call it from init(), like database/sql drivers.
func Register(name string, ctor func() Notifier) { registry[name] = ctor }
// New is the creation point. The caller asks for a kind, not a type.
func New(kind string) (Notifier, error) {
ctor, ok := registry[kind]
if !ok {
names := make([]string, 0, len(registry))
for k := range registry {
names = append(names, k)
}
sort.Strings(names)
return nil, fmt.Errorf("unknown notifier %q (have %v)", kind, names)
}
return ctor(), nil
}
func init() {
Register("email", func() Notifier { return emailNotifier{from: "noreply@shop.test"} })
Register("sms", func() Notifier { return smsNotifier{} })
}
func main() {
for _, kind := range []string{"email", "sms", "fax"} {
n, err := New(kind)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Println(n.Notify("ali", "order shipped"))
}
}Structural: Decorator for io.Reader and http.Handler Must-know
The same shape, twice. A wrapper has the same interface as the thing it wraps, forwards the call and adds behaviour. Chain makes the first middleware the outermost layer.
// Structural family: Decorator. The same shape appears twice in the standard library:
// io.Reader wrappers and net/http middleware (func(http.Handler) http.Handler).
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
)
// countingReader decorates any io.Reader and counts the bytes that pass through.
type countingReader struct {
io.Reader
n int
}
func (c *countingReader) Read(p []byte) (int, error) {
n, err := c.Reader.Read(p)
c.n += n
return n, err
}
// Middleware is a decorator of http.Handler.
type Middleware func(http.Handler) http.Handler
// Chain wraps h so that the first middleware is the outermost layer.
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("log: before", r.URL.Path)
next.ServeHTTP(w, r)
fmt.Println("log: after", r.URL.Path)
})
}
func requireKey(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Key") != "secret" {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
cr := &countingReader{Reader: strings.NewReader("hello decorator")}
data, _ := io.ReadAll(io.LimitReader(cr, 5)) // decorators compose: Limit(Counting(Strings))
fmt.Printf("read %q, counted %d\n", data, cr.n)
app := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "ok") })
h := Chain(app, logging, requireKey)
for _, key := range []string{"", "secret"} {
req := httptest.NewRequest(http.MethodGet, "/orders", nil)
req.Header.Set("X-Key", key)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println("status", rec.Code)
}
}Behavioral: Strategy and Observer without classes Must-know
A function type is the Strategy interface; a slice of callbacks is the Observer. Nothing to subclass.
// Behavioral family: Strategy and Observer without class hierarchies.
// A function type is the strategy interface; a slice of callbacks is the subject.
package main
import "fmt"
// Discount is a Strategy: any function with this signature can be plugged in.
type Discount func(cents int) int
func none(c int) int { return c }
func tenPercent(c int) int { return c - c/10 }
func flat(off int) Discount { return func(c int) int { return max(c-off, 0) } }
// Checkout depends on the strategy, not on any concrete rule.
type Checkout struct {
discount Discount
observers []func(event string, cents int)
}
// Subscribe registers an Observer.
func (c *Checkout) Subscribe(f func(event string, cents int)) {
c.observers = append(c.observers, f)
}
func (c *Checkout) Pay(cents int) int {
total := c.discount(cents)
for _, o := range c.observers {
o("paid", total)
}
return total
}
func main() {
rules := []struct {
name string
d Discount
}{{"none", none}, {"10%", tenPercent}, {"flat 500", flat(500)}}
for _, r := range rules {
name, c := r.name, &Checkout{discount: r.d}
c.Subscribe(func(ev string, cents int) { fmt.Printf(" [audit] %s %d\n", ev, cents) })
fmt.Println(name, "->", c.Pay(2000))
}
}The Go angle
Go gives you three tools that cover most of GoF chapter 1: small implicit interfaces ("program to an interface"), struct embedding and field composition ("favor composition"), and first-class functions (Command, Strategy, Template Method with a function argument). What it does not give you is inheritance, so Template Method and Visitor take different shapes.
Idiom, not pattern: functional options. It replaces Builder because Go has no default arguments:
// Idiom, not a GoF pattern: functional options (Rob Pike, "Self-referential functions
// and the design of options", 2014). Go has no default arguments and no overloading,
// so an option is a function that mutates the value under construction.
package main
import (
"fmt"
"time"
)
type Server struct {
addr string
timeout time.Duration
tls bool
}
// Option is the whole idiom: a function on *Server.
type Option func(*Server)
func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }
func WithTLS() Option { return func(s *Server) { s.tls = true } }
// NewServer has sane defaults; options override them. Adding an option never breaks callers.
func NewServer(addr string, opts ...Option) *Server {
s := &Server{addr: addr, timeout: 30 * time.Second}
for _, o := range opts {
o(s)
}
return s
}
func main() {
fmt.Printf("%+v\n", *NewServer(":8080"))
fmt.Printf("%+v\n", *NewServer(":8443", WithTLS(), WithTimeout(5*time.Second)))
}Patterns already in the standard library, with the real functions:
// Patterns that already live in the Go standard library, used without naming them.
package main
import (
"bytes"
"context"
"fmt"
"io"
"sort"
"strings"
)
type byLen []string
func (b byLen) Len() int { return len(b) }
func (b byLen) Less(i, j int) bool { return len(b[i]) < len(b[j]) }
func (b byLen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
type ctxKey string
func main() {
// Adapter / Decorator: io.Reader pipelines. MultiReader concatenates, LimitReader caps,
// TeeReader copies what passes through to a second writer.
var seen bytes.Buffer
r := io.TeeReader(io.LimitReader(io.MultiReader(strings.NewReader("abc"), strings.NewReader("defgh")), 6), &seen)
out, _ := io.ReadAll(r)
fmt.Printf("out=%s seen=%s\n", out, seen.String())
// Strategy / Template Method: sort.Sort owns the algorithm, the type owns the ordering.
words := byLen{"pattern", "go", "factory", "io"}
sort.Sort(sort.Reverse(words)) // Reverse is itself a decorator over sort.Interface
fmt.Println(words)
// Chain: every context wraps its parent; Value walks the chain, cancellation flows down.
root, cancel := context.WithCancel(context.Background())
child := context.WithValue(root, ctxKey("user"), "ali")
cancel()
fmt.Println(child.Value(ctxKey("user")), child.Err())
}Laravel
Creational: the container is the factory Must-know
Controllers and services type-hint an interface; the container decides which class to build and for whom (bind, singleton, when(...)->needs(...)->give(...)). There is no new in application code.
<?php
// Creational family in Laravel: the service container is a factory plus a registry.
// Binding an interface to a closure is Factory Method; singleton() is a managed Singleton.
namespace App\Providers;
use App\Contracts\Notifier;
use App\Notifications\EmailNotifier;
use App\Notifications\SmsNotifier;
use App\Services\Checkout;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
final class NotificationServiceProvider extends ServiceProvider
{
public function register(): void
{
// Factory Method: callers type-hint Notifier and never call "new".
$this->app->bind(Notifier::class, function (Application $app): Notifier {
return match (config('notify.driver')) {
'sms' => new SmsNotifier(config('notify.sms.key')),
default => new EmailNotifier($app->make('mailer')),
};
});
// One instance per application (Singleton, but owned by the container, not by a static field).
$this->app->singleton(SmsNotifier::class, fn () => new SmsNotifier(config('notify.sms.key')));
// Contextual binding: the same interface, a different product for one consumer.
$this->app->when(Checkout::class)
->needs(Notifier::class)
->give(SmsNotifier::class);
}
}Structural: Decorator around a repository Must-know
CachedPriceRepository implements the same interface as DbPriceRepository and wraps it. The provider binds the decorated version; callers do not change.
<?php
// Structural family: Decorator over a repository contract, plus how a facade is a proxy.
namespace App\Repositories;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Support\Facades\DB;
interface PriceRepository
{
public function priceOf(int $productId): int;
}
final class DbPriceRepository implements PriceRepository
{
public function priceOf(int $productId): int
{
return (int) DB::table('products')->where('id', $productId)->value('price_cents');
}
}
// Decorator: same interface, wraps another implementation, adds caching.
final class CachedPriceRepository implements PriceRepository
{
public function __construct(
private readonly PriceRepository $inner,
private readonly Cache $cache,
) {}
public function priceOf(int $productId): int
{
return $this->cache->remember("price:{$productId}", 300, fn () => $this->inner->priceOf($productId));
}
}
// In a service provider (shown as a comment to keep this file a single concern):
//
// $this->app->bind(PriceRepository::class, fn ($app) => new CachedPriceRepository(
// $app->make(DbPriceRepository::class),
// $app->make('cache.store'),
// ));
//
// Proxy: Illuminate\Support\Facades\Cache::get('k') is __callStatic() on the Facade base class,
// which resolves the real object from the container and forwards the call to it.Behavioral: Pipeline and events Must-know
Each pipe gets the payload and a $next closure and decides whether to continue. The publisher of an event knows only the event class.
<?php
// Behavioral family: Chain of Responsibility (Pipeline) and Observer (events).
namespace App\Services;
use App\Events\OrderPlaced;
use App\Listeners\SendInvoice;
use Closure;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Pipeline;
final class PriceQuote
{
public function __construct(public int $cents) {}
}
// Each stage receives the quote and a $next closure; it may change the quote or stop the chain.
final class ApplyCoupon
{
public function handle(PriceQuote $quote, Closure $next): mixed
{
$quote->cents -= 500;
return $next($quote);
}
}
final class AddTax
{
public function handle(PriceQuote $quote, Closure $next): mixed
{
$quote->cents = (int) round($quote->cents * 1.09);
return $next($quote);
}
}
final class QuoteService
{
public function total(int $cents): int
{
return Pipeline::send(new PriceQuote($cents))
->through([ApplyCoupon::class, AddTax::class])
->thenReturn()
->cents;
}
}
// Observer: the publisher knows only the event; listeners subscribe from outside.
// Event::listen(OrderPlaced::class, SendInvoice::class);
// OrderPlaced::dispatch($order);The Laravel angle
Laravel is class-based, so patterns look close to the book, but it hides most of the plumbing:
| What you write | Pattern behind it | Where the plumbing lives |
|---|---|---|
app(Notifier::class) or constructor injection | Factory Method + DI | Container |
Cache::remember(...) | Proxy to the cache binding, Strategy for the store | Facade, CacheManager |
Event::listen, #[ObservedBy] | Observer | Dispatcher, Eloquent events |
Route::middleware(...) | Chain of Responsibility | HTTP kernel, Pipeline |
dispatch(new Job(...)) | Command | Queue |
Order::where(...)->first() | Active Record + fluent Builder | Eloquent, query builder |
PHP idioms that remove small patterns:
<?php
// PHP idioms that replace small pattern implementations. Not GoF patterns.
namespace App\Domain;
// Constructor promotion + readonly: a value object without getters or a builder.
final class Money
{
public function __construct(
public readonly int $cents,
public readonly string $currency = 'EUR',
) {}
public function with(int $cents): self
{
return new self(cents: $cents, currency: $this->currency);
}
}
// Backed enum + match: State/Strategy for a closed set of cases, no class per case.
enum Shipping: string
{
case Standard = 'standard';
case Express = 'express';
public function fee(Money $order): Money
{
return $order->with(match ($this) {
self::Standard => $order->cents >= 5000 ? 0 : 499,
self::Express => 1499,
});
}
}
// First-class callable syntax: a Strategy is just a Closure.
$discounts = ['half' => fn (int $c): int => intdiv($c, 2), 'none' => fn (int $c): int => $c];
$apply = $discounts['half'];
$total = $apply(2000);
// Named arguments replace the "telescoping constructor" that motivates Builder.
$m = new Money(currency: 'USD', cents: 1200);The Eloquent row deserves a look at what it sends to the database. Active Record means the object saves itself; the SQL is the same you would write by hand, and DB::transaction is the Unit of Work boundary:
-- $order = Order::create(['user_id' => 7, 'total_cents' => 1999]); (Active Record)
BEGIN; -- DB::transaction(...) = the unit of work
INSERT INTO orders (user_id, total_cents, created_at, updated_at)
VALUES (7, 1999, now(), now()) RETURNING id; -- model->save() generates this
INSERT INTO outbox (event, order_id) VALUES ('OrderPlaced', 1); -- observer / listener side effect
COMMIT;Mechanics: reading and applying a pattern
The selection procedure Must-know
In plain words: name the pain, find the candidates, read the consequences, apply the smallest one.
Common misunderstanding: "The pattern chooser is the family." You choose by the force that is hurting: what varies? GoF chapter 1 frames the whole book that way (encapsulate what varies).
| Force: what varies | Candidates | Cheapest first |
|---|---|---|
| Which class gets created | Factory Method, Abstract Factory, Prototype | A constructor function |
| How an object is configured | Builder | Functional options, named arguments |
| The algorithm | Strategy, Template Method | A function parameter |
| Behaviour that depends on state | State | A switch on an enum |
| Optional extra behaviour stacked in any order | Decorator, Chain of Responsibility | A wrapper function |
| Incompatible interface | Adapter, Facade | A small wrapper type |
| Who is notified | Observer, Mediator | A callback list |
| Operation on a tree of types | Composite, Visitor | A recursive function |
| Request to queue, retry, undo | Command, Memento | A job class |
The consequences check, before writing any code
1 Problem named in one sentence (not "we need a Factory")
2 Smell visible in the current code (or a second implementation exists)
3 Smallest tool tried first: function, interface, wrapper
4 Pattern chosen; Consequences section read aloud
5 Name used in the code (Notifier, ...Decorator) and in the PR description
6 Test that proves the variation point (two implementations or a fake)Consequences table: what each family costs Important
| Family | You gain | You pay | Typical failure |
|---|---|---|---|
| Creational | Callers do not know concrete classes; creation is testable | A new type or registry; indirection when reading | Factory of factories |
| Structural | Reuse and flexible assembly without editing old code | Many small objects; stack traces through wrappers | Wrapper that must forward 20 methods |
| Behavioral | Variation behind a stable interface; loose coupling | Control flow becomes hard to trace | Observers that trigger observers |
| Concurrency | Throughput and isolation | Ordering, deadlock, shutdown complexity | Unbounded queues |
| Enterprise | A place for persistence and use-case code | Mapping layers, magic | Active Record models with 3,000 lines |
| Architectural | Whole-system qualities | Hard to change later | Layers that leak |
| Messaging | Decoupling in time and space | Eventual consistency, duplicates | Missing idempotency |
Solving the classic problems
Classic problem: learning patterns without applying them blindly Important
| Approach | How | Advantage | Cost |
|---|---|---|---|
| Problem-first reading | Start from a smell in your code, find the pattern in the catalogue | You learn the consequences with a real case | Slower than reading the book cover to cover |
| Kata | Write the same small problem twice: plain and with the pattern | You feel the bill | Needs discipline |
| Read real code | Open io, net/http, Laravel's Pipeline.php and name what you see | Known uses are the best teachers | Needs the vocabulary first (this page) |
| Review checklists | Ask "which problem?" and "what are the consequences?" in every PR | Stops pattern-itis | Needs team buy-in |
| Refactoring to Patterns | Let the smell appear, refactor in small steps | Patterns arrive when needed | Needs tests |
Classic problem: the pattern's name does not appear in the code Good to know
If a team uses the vocabulary only in meetings, new readers cannot find the shape. Put the pattern word in the type name where it adds meaning (CachedPriceRepository, RetryDecorator, DiscountStrategy), and not where it only adds noise (ManagerFactoryHelper). Link to the ADR from the package doc when the decision was non-obvious.
Choosing: which pattern, and is a pattern needed at all
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| One rule today, no second in sight | No pattern | Keep it a plain function | Indirection must be paid for by variation |
| Two or three alternatives that grow | Strategy | Function type in Go, contract in PHP | Behind one interface the call site stays stable |
| Cross-cutting concern around a call (log, retry, cache) | Decorator or middleware | Chain with Chain(h, mws...) or Pipeline | Order is explicit and composable |
Tangled new calls and driver switch | Factory Method | Registry in Go, container binding in Laravel | One place knows the concrete class |
| Many optional settings | Builder idiom | Functional options, named arguments | No telescoping constructors |
| An object with a life cycle (draft, paid, shipped) | State | Enum plus match first | A closed set rarely needs a class per state |
| React to something that happened | Observer | Events in Laravel, callbacks or channels in Go | Publisher does not know subscribers |
| Third-party API that will change | Adapter | Own interface in your domain | Protects the rest of the code |
| Complicated subsystem, many callers | Facade | A service class per use case | One entry point per actor |
| Persistence of the domain | Repository or Active Record | See Data persistence | Pick by domain complexity |
| Cross-process coordination | Not a GoF pattern | Outbox, Saga, messaging | The problem is distribution |
Selection, combination and anti-patterns in real systems continue in Patterns in practice.
In architecture: from a single process to a distributed system
Monolith: one process, one database
Everyday example: a shop checkout. One Laravel app. Factory Method is the container building PaymentGateway; Strategy is the discount rule; Observer is OrderPlaced sending the invoice; Active Record is Order; Pipeline applies coupon, tax, shipping. All of it is in one process: a pattern costs a few classes and a failing test is one phpunit run. Start plain; extract an interface when the second implementation or the test needs it.
Production example: Laravel itself. Illuminate\Pipeline\Pipeline builds a chain of closures with array_reduce; the HTTP kernel runs middleware through it; Eloquent events dispatch observers; Manager::driver() creates cache stores. It is one codebase, one process, five patterns, used by millions of applications.
Modular monolith and multiple databases
Patterns move from classes to module boundaries. A module's public API is a Facade; a port with an adapter is an Anti-Corruption layer when another module changes its model; the Observer becomes a domain event crossing the boundary. A rule of thumb: patterns inside a module serve the module; patterns on the boundary serve the team that owns the other side. See Modular monolith.
| Boundary concern | Pattern | Why |
|---|---|---|
| Billing calls Inventory | Facade on Inventory, interface in Billing | Billing does not know Inventory's models |
Reaction to OrderPlaced | Observer via an in-process event bus | Same transaction, easy to test |
| Reports read orders | Repository or query object per module | Only the owner reads its tables |
Microservices: patterns across a network
Everyday example. Checkout in Go calls Payments over HTTP. The Go http.Client with a RoundTripper wrapper is a Decorator that adds retries and a timeout; a generated gRPC client is a Proxy; the API gateway is a Facade.
Production example. The Observer becomes a message on a broker; it no longer shares a transaction. The Command becomes a message; the Mediator becomes an orchestrator. These variants have their own names, catalogues and failure modes: Outbox, Saga, Dead-letter queue, Message acknowledgment. A GoF Observer has no retry, ordering or duplicates problem; a messaging Observer has all three.
Same intent, different guarantees
1 In-process Observer notify() calls listeners in order; failure = exception; same transaction
2 Broker publish at-least-once; consumer may see the event twice; separate transaction
3 Therefore need idempotent consumers, outbox for publish, DLQ for poison messagesDistributed data: replicas, caches and consistency
Caching is a Decorator or Proxy at the call level: CachedPriceRepository wraps the database repository. The pattern says nothing about staleness. With read replicas or a shared Redis, the cache decorator now also owns invalidation and the question "what does a reader see after a write?" (see Replication and failover, Redis). Patterns give the shape; the distributed systems chapters supply the guarantees.
| Pattern at code level | What breaks in a distributed setting |
|---|---|
| Singleton | One per process is not one per cluster (a "singleton" job runs on every pod) |
| Observer | Delivery is no longer reliable or ordered |
| Chain of Responsibility | A handler may time out or be unavailable |
| Memento | A snapshot must survive restarts and be versioned |
| Command | Must be idempotent to be retried safely |
Scaling path: 1×, 10×, 100×
| Load | What patterns do |
|---|---|
| 1× (one developer, one service) | Few patterns, most of them from the framework; resist adding more |
| 10× (several teams, one codebase) | Facade per module, Strategy for what varies per customer, Decorator for caching and observability |
| 100× (many services, many regions) | Patterns from other catalogues dominate: Outbox, Saga, Circuit Breaker, CQRS; GoF patterns remain inside each service |
Lab: find the patterns in code you already have
Setup: cd docs/snippets/design/design-patterns-introduction/go && go version (needs Go 1.24).
Run the three families.
textgo run ./creational # email and sms notifiers, then the unknown "fax" error go run ./structural # 403 without a key, 200 with it; log lines wrap the handler go run ./behavioral # three discounts, each producing an audit line via the observerExpected: the output in the comments of each file. Add a
pushnotifier by callingRegisteronce;Newdoes not change.Break the Decorator order. In
structural, swaplogging, requireKeyforrequireKey, logging. Predict which requests log before running. (Answer: the forbidden request no longer logs, becauserequireKeyis now outermost.)Find patterns in the standard library.
textgo doc io.TeeReader go doc net/http.StripPrefix go doc sort.Reverse go doc context.WithValueFor each, write one line: which GoF pattern, and which interface it wraps.
Find them in Laravel. In a Laravel 13 project:
grep -n "array_reduce" vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.phpand readcarry();grep -n "__callStatic" vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php;grep -n "customCreators" vendor/laravel/framework/src/Illuminate/Support/Manager.php. Write the pattern next to each hit.Refactor toward a pattern. Take this plain function and extract a Strategy only when the second rule exists:
textfunc total(c int, kind string) int { if kind == "ten" { return c - c/10 } return c }Then add
"flat"and observe which smell appears (Switch Statements), and applyDiscount func(int) intfrombehavioral/main.go.Remove a pattern. Pick one interface in your own code with a single implementation and no test double. Inline it. Does anything get worse?
Common misconceptions
| Belief | Reality |
|---|---|
| Patterns are reusable code | They are descriptions; code is written per language and problem |
| The GoF book is the only pattern catalogue | It is one catalogue; PoEAA, EIP, POSA, DDD and PLoP collections exist |
| There are 23 patterns | There are 23 GoF patterns; thousands across catalogues |
| Patterns only work in OO languages | Alexander's came from buildings; Go uses them with interfaces and functions |
| Using more patterns means better design | Each pattern is a cost; use the smallest that solves the problem |
| Singleton is a good way to share state | It hides a dependency; let the container or main own lifetime |
| Laravel facades are the Facade pattern | They are static proxies to container objects |
| Active Record is bad and Data Mapper is good | Each fits different domains; trade-offs are on Data persistence |
| Norvig showed patterns are obsolete | He showed 16 of 23 are simpler with the right language features, and endorsed patterns as vocabulary |
| Family names tell you when to use a pattern | They group by purpose; choose by the problem that hurts |
| Patterns replace principles | Principles judge a design; patterns offer shapes |
| A pattern name in the class name makes the code better | Only if it carries meaning; ManagerFactoryHelper does not |
Cheat sheet
| Topic | Remember |
|---|---|
| Origin | Alexander 1977 (253 patterns) to Beck and Cunningham 1987 to GoF 1994 |
| GoF counts | 23 patterns: 5 creational, 7 structural, 11 behavioral |
| Template | Name, Intent, Motivation, Applicability, Structure, Participants, Collaborations, Consequences, Implementation, Known uses, Related |
| Read order | Intent, Applicability, Consequences first; Structure last |
| Not | A library, a goal, copy-paste code |
| Idiom vs pattern | Idioms are language-specific (functional options); patterns are design-level |
| Principle vs pattern | Principles judge; patterns propose |
| Smell | Start from the pain; refactor toward the pattern (Kerievsky) |
| Norvig | 16 of 23 simpler with first-class functions, types, macros, modules |
| Go | Small interfaces, composition, functions: Strategy, Command, Visitor shrink; Decorator and Chain stay |
| PHP / Laravel | Container = factory + DI, Pipeline = Chain, Events = Observer, Eloquent = Active Record, drivers = Strategy |
| Beyond GoF | Concurrency, PoEAA, architecture, messaging patterns |
| Anti-pattern | Pattern-itis: interface with one implementation, factory of factories |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What did Alexander contribute to software design, and in what form did Beck and Cunningham adopt it? Good to know
Answer
Answer: Alexander's 1977 A Pattern Language describes 253 patterns as hypotheses that connect into a language. Beck and Cunningham (OOPSLA-87) applied the idea to Smalltalk window design with five patterns. See Where it comes from.
2 — How many GoF patterns are there in each family? Must-know
Answer
Answer: Five creational, seven structural, eleven behavioral: 23 in total. See the table.
3 — Why is the class diagram not the whole pattern? Must-know
Answer
Answer: The diagram is only the Structure section. Strategy and State share a diagram; Intent, Applicability and Consequences tell them apart. See the template.
4 — Name three things a pattern is not. Must-know
Answer
Answer: Not a library or code you can import, not a goal of a design, and not a recipe with one right form. See What patterns are not.
5 — Is Repository a GoF pattern? Where does it come from? Important
Answer
Answer: No. It is in Fowler's PoEAA catalogue (Object-Relational Metadata Mapping Patterns) and in DDD. See Families beyond GoF.
6 — What is the difference between functional options and Builder? Important
Answer
Answer: Same problem (many optional settings), different level: Builder is a design pattern, functional options is a Go idiom that exists because Go has no default arguments or overloading. See Pattern vs idiom.
7 — What did Norvig claim, and what did he not claim? Good to know
Answer
Answer: 16 of 23 patterns are simpler or invisible in Lisp or Dylan thanks to first-class types, functions, macros, method combination, multimethods and modules. He did not claim patterns are useless. See Norvig.
8 — Which Laravel feature is the Observer pattern, which is Chain of Responsibility, and which is Active Record? Must-know
Answer
Answer: Events and listeners; Pipeline and HTTP middleware; Eloquent models. See Laravel.
9 — Why is Laravel's Collection::macro not exactly Decorator? Good to know
Answer
Answer: It adds methods to a class at runtime through Macroable, it does not wrap an instance with the same interface. It is closer to an open class or extension object. See Laravel.
10 — A teammate adds an interface with a single implementation "for flexibility". What do you ask? Must-know
Answer
Answer: Which problem exists today, and what varies? If nothing, inline it; extract the interface when a second implementation or a test double needs it. See Pattern-itis.
11 — What changes when an in-process Observer becomes a message on a broker? Important
Answer
Answer: You lose the shared transaction and gain at-least-once delivery, possible duplicates and ordering issues; you need idempotent consumers, an outbox and a DLQ. See Microservices.
Glossary
| Term | Meaning |
|---|---|
| Design pattern | A named, documented solution to a recurring design problem, with its consequences |
| Pattern language | A set of patterns that refer to each other and are used in a sequence (Alexander) |
| Catalogue | A collection of patterns in one template (GoF, PoEAA, EIP) |
| GoF (Gang of Four) | Gamma, Helm, Johnson, Vlissides; authors of the 1994 Design Patterns |
| Creational pattern | Pattern about object creation |
| Structural pattern | Pattern about assembling objects into larger structures |
| Behavioral pattern | Pattern about algorithms and responsibilities between objects |
| Concurrency pattern | Pattern for coordinating threads, goroutines or processes |
| Enterprise application pattern | Pattern from Fowler's PoEAA for persistence, domain logic and presentation |
| Architectural pattern | Pattern for the structure of a whole system |
| Messaging and integration pattern | Pattern from Hohpe and Woolf's EIP for communication between processes |
| PLoP | Pattern Languages of Programs, the conference run by the Hillside Group |
| Hillside Group | The community that promotes patterns and runs PLoP |
| Intent | One sentence saying what problem a pattern solves |
| Motivation | A concrete scenario that shows the problem |
| Applicability | When to use the pattern |
| Participants | The roles (classes or functions) in a pattern |
| Consequences | The trade-offs of applying the pattern |
| Known uses | Real systems where the pattern appears |
| Idiom | A language-specific way to write a small construct |
| Functional options | Go idiom: option functions passed to a constructor (Pike, 2014) |
| Principle | A rule used to judge designs, such as SOLID |
| Code smell | A symptom in code that suggests a design problem |
| Refactoring to Patterns | Kerievsky's method: reach a pattern by small refactorings from a smell |
| Pattern-itis | Using patterns without a problem to solve |
| Speculative Generality | Smell: abstractions added for needs that do not exist yet |
| Invisible / informal / formal pattern | Norvig's levels: built into the language, described in prose, or implemented as reusable code |
| Active Record | Fowler: an object that wraps a row, handles DB access and adds domain logic; Eloquent |
| Service container | Laravel's dependency injection container; a factory and registry |
| Facade (Laravel) | Static-looking class that proxies to a container object via __callStatic |
| Pipeline | Laravel's chain of pipes, each receiving a payload and a $next closure |
| Manager | Laravel class that creates a driver by name (CacheManager) |
| Macroable | Laravel trait that lets you add methods to a class at runtime |
io.Reader decorator | Go wrapper type implementing io.Reader around another reader |
http.Handler middleware | A function that takes a handler and returns a handler |
References
- Christopher Alexander, Sara Ishikawa, Murray Silverstein et al., A Pattern Language: Towns, Buildings, Construction, Oxford University Press, 1977. Read through Wikipedia, A Pattern Language (secondary source; the book itself was not read)
- Kent Beck, Ward Cunningham, Using Pattern Languages for Object-Oriented Programs, Technical Report CR-87-43, 17 September 1987
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994. Read through Wikipedia, Design Patterns (secondary source) and the refactoring.guru catalogue
- Wikipedia, Software design pattern (history, criticism; secondary source)
- Refactoring.guru, What's a design pattern?, Criticism of patterns
- The Hillside Group, Home and mission
- Peter Norvig, Design Patterns in Dynamic Programming, Object World, 5 May 1996 (page: Design Patterns in Dynamic Languages)
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, 5 March 2003; Active Record
- Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004
- Gregor Hohpe, Bobby Woolf, Enterprise Integration Patterns
- Rob Pike, Self-referential functions and the design of options, 2014
- Go: Effective Go, package io, net/http, sort, context, Go 1.23 release notes
- Laravel 13: Service Container, Facades, Events, Eloquent, Query Builder, Middleware, Cache, Collections
- Laravel framework source (13.x): Pipeline.php, Facade.php, Manager.php, Macroable.php
- PHP manual: Generators, Enumerations