Skip to content

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 forGo to
The whole page in a few tablesEverything in one minute
Why patterns exist and what they tradeWhy patterns exist
Alexander, Beck and Cunningham, GoF, PLoP, NorvigWhere it comes from
The 23 GoF patterns by family with intent and chapter linksThe 23 patterns in one table
Name, intent, motivation, structure, consequencesThe pattern template
What patterns are not (library, goal, recipe)What patterns are not
Creational, structural, behavioral and the families beyond GoFThe families
Idiom vs pattern vs principle vs architecturePatterns, idioms and principles
Smells, Refactoring to PatternsPatterns and code smells
Norvig, "missing language feature", pattern-itisCriticism
Which patterns are trivial in Go or PHPModern relevance in Go and PHP
Where each pattern already hides in Laravel and GoWhere patterns already live
One pattern per family in Go and LaravelGo, Laravel
How to pick a patternChoosing
Monolith to distributed systemsIn architecture
Hands-on grep and run exercisesLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked later.

TermIn plain wordsTiny exampleWhat goes wrong without it
PatternA named solution to a recurring problem in a context, with its trade-offs"Strategy": swap the discount ruleEvery team re-invents the idea and calls it something else
Pattern languagePatterns that reference each other in an orderBeck and Cunningham's five Smalltalk window patternsA bag of unrelated tricks
CatalogueA book or site listing patterns in one templateGoF, PoEAA, EIPPatterns are folklore, not reference
IdiomA language-specific way to write something smallGo functional optionsConfused with a design-level decision
PrincipleA rule of thumb that judges designsSingle ResponsibilityPatterns applied without a reason
SmellA symptom in code that suggests a design problemLong switch on typeYou add a pattern where nothing hurts
Pattern-itisUsing patterns because they exist, not because a problem existsAbstractUserFactoryProviderCode nobody can follow

The three GoF families and the question each answers.

FamilyCountQuestion it answersTypical example
Creational5How do I make objects without hard-wiring the concrete class?Factory Method
Structural7How do I assemble objects into bigger structures?Decorator
Behavioral11Who does what, and how do objects talk?Strategy

Beyond GoF.

FamilyScaleWhere it is taught
Concurrency patternsThreads, goroutines, queuesDesigning for concurrency
Enterprise application patterns (Fowler, PoEAA)Persistence and domain logic of one applicationData persistence in design
Architectural patternsWhole systemStyles vs patterns
Messaging and integration patterns (Hohpe and Woolf, EIP)Between processesMessaging fundamentals

Where patterns live in your tools.

LevelGoLaravel
CreationNewX functions, registries like database/sqlService container bindings
Wrappingio.Reader wrappers, http.Handler middlewareCache decorators, middleware, Pipeline
Behaviour swapsort.Interface, function typesCache and queue drivers, closures
NotificationChannels, callbacksEvents and listeners, Eloquent observers
Persistencedatabase/sql plus your repositoryEloquent (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 vocabularyWith a catalogue of patterns
Every design discussion starts from objects and arrowsStart from "this is a Strategy, with these consequences"
New hires learn by reading the whole codebaseNew hires recognise shapes they have seen in other systems
A trade-off is discovered in productionThe known consequences are listed before you build
Reviews argue about tasteReviews argue about which problem is being solved
Cost: you must learn the namesCost: names can hide the simple solution, and can be over-applied
1977AlexanderA Pattern Language1987Beck + CunninghamOOPSLA, Smalltalk1994GoF book, 23 patternsfirst PLoP conference1996Norvig: 16 of 23simpler in Lisp/Dylan2003Fowler PoEAA catalogueenterprise patterns2004KerievskyRefactoring to Patterns

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 ​

  1. "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.
  2. "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.
  3. "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.Handler chain 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.

text
     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 Patterns

The 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.

PatternFamilyOne-line intentChapter
SingletonCreationalExactly one instance, with a global access pointSingleton
Factory MethodCreationalLet a method decide which concrete class to createFactory Method
Abstract FactoryCreationalCreate families of related objects without naming concrete classesAbstract Factory
BuilderCreationalBuild a complex object step by stepBuilder
PrototypeCreationalCreate new objects by copying an existing onePrototype
AdapterStructuralMake one interface look like anotherAdapter
BridgeStructuralSeparate an abstraction from its implementation so both varyBridge
CompositeStructuralTreat a tree of objects and a single object the same wayComposite
DecoratorStructuralAdd behaviour by wrapping an object with the same interfaceDecorator
FacadeStructuralOne simple entry point to a complex subsystemFacade
FlyweightStructuralShare small immutable objects to save memoryFlyweight
ProxyStructuralA stand-in that controls access to another objectProxy
Chain of ResponsibilityBehavioralPass a request along handlers until one handles itChain of Responsibility
CommandBehavioralTurn a request into an object you can queue, log and undoCommand
InterpreterBehavioralRepresent a small grammar and evaluate sentences of itBehavioral patterns
IteratorBehavioralWalk a collection without exposing its structureIterator
MediatorBehavioralLet objects talk through one coordinator instead of each otherMediator
MementoBehavioralCapture and restore an object's state without breaking encapsulationMemento
ObserverBehavioralNotify dependants when something changesObserver
StateBehavioralChange behaviour when the internal state changesState
StrategyBehavioralMake an algorithm interchangeable at runtimeStrategy
Template MethodBehavioralFix the skeleton of an algorithm, let steps varyTemplate Method
VisitorBehavioralAdd operations to a class hierarchy without editing the classesVisitor

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 ​

1. Name (a shared word)The problem2. Intent: one sentence3. Motivation: a concrete case4. Applicability: when to reach for it"Do I have this problem?"The solution5. Structure: class diagram6. Participants: the roles7. Collaborations: who calls whom8. Implementation: hints, traps"What shape does the fix take?"The evidence and the price9. Consequences: trade-offs10. Known uses: real systems11. Related patterns: neighbours"Is it worth it, and what else?"

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".

SectionQuestion it answersExample, for Decorator
NameWhat do we call it in a code review?Decorator (also known as Wrapper)
IntentWhat problem does it solve, in one sentence?Add behaviour to an object without changing its class
MotivationA concrete scenario where the problem hurtsLogging, caching and auth around one handler
ApplicabilityWhen should I reach for it, when not?Several optional behaviours that combine in any order
StructureWhat are the classes and arrows?Component, ConcreteComponent, Decorator holding a Component
ParticipantsWhat role does each class play?Component is the interface, decorators implement it too
CollaborationsWho calls whom at runtime?The decorator forwards to the wrapped component
ConsequencesWhat do I gain and pay?Flexible, but many small objects and a hard-to-read stack trace
ImplementationHints and trapsKeep the interface small, or wrappers must forward everything
Known usesWhere does it already exist?io.Reader wrappers, http.Handler middleware
Related patternsWhat 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.

text
     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."

ThingYou getYou must write
Library function (sort.Slice)Working code, testedA call
Framework (Laravel)A skeleton that calls your codeYour hooks
Pattern (Strategy)A name, an intent, consequencesThe code, fitted to your types
Algorithm (quicksort)Precise stepsTheir 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 reasonUnhealthy 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 ​

GoF 1994: 23 patterns, objects and classes in one processCreational (5)SingletonFactory Method, Abstract FactoryBuilder, Prototypehow objects are madeStructural (7)Adapter, Bridge, CompositeDecorator, FacadeFlyweight, Proxyhow objects are assembledBehavioral (11)Chain of Responsibility, CommandInterpreter, Iterator, MediatorMemento, Observer, State, StrategyTemplate Method, Visitorwho does what, who talks to whomother catalogues, other scalesConcurrencyworker pool, pipelinefan-out/fan-in, actorgoroutines, queuesEnterprise (PoEAA)Active Record, Data MapperRepository, Unit of Workpersistence, domain logicArchitecturallayers, hexagonal, CQRSpipe-and-filterwhole-system structureMessaging (EIP)Outbox, Saga, DLQRouter, Translatorbetween processes

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.

FamilyRefactoring.guru's one-line definitionPatterns
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
text
     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.

FamilyCatalogueExamplesScaleTaught in
ConcurrencySchmidt et al., POSA 2; Go blog on pipelinesWorker pool, pipeline, fan-out/fan-in, actorOne process, many threads or goroutinesConcurrency design
Enterprise applicationFowler, PoEAA (2003 page)Active Record, Data Mapper, Repository, Unit of Work, Identity Map, Lazy Load, Service Layer, Front Controller, DTOOne application and its databaseData persistence, Repositories
ArchitecturalBuschmann et al. POSA 1; Bass, Clements, KazmanLayers, pipe-and-filter, microkernel, hexagonalWhole systemStyles vs patterns, Layered monolith
Messaging and integrationHohpe and Woolf, EIPMessage Channel, Content-Based Router, Translator, Outbox, Saga, Dead Letter ChannelBetween processesMessaging fundamentals, Outbox, Saga, Dead-letter queue
PresentationFowler PoEAA; Smalltalk MVCMVC, Page Controller, Front Controller, Template ViewUI layerMVC, MVP, MVVM
Domain-driven designEvans, 2003Aggregate, Factory, Repository, Domain EventOne bounded contextAggregates and factories
Organisational and processCoplien; the Hillside collectionPatterns for teams and processesPeopleHillside 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.

QuestionPatternIdiom
ScopeSeveral types and their relationsOne construct or a few lines
LanguageMostly language-independentSpecific to one language
Example in GoDecorator, StrategyFunctional options, defer to unlock, errors.Is, return error last
Example in PHPObserver, ChainConstructor promotion, readonly, enum with match, named arguments
Where documentedCatalogues (GoF, PoEAA)Language guides (Effective Go, PHP manual)
Failure when ignoredReinvented design, naming driftCode 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).

text
     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 arguments

Pattern 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.

PrinciplePattern that often follows from it
Single ResponsibilityFacade (one entry per actor), Command (one use case per class)
Open–ClosedStrategy, Decorator, Template Method, Observer
Liskov SubstitutionConstrains every pattern that relies on subtypes (State, Strategy)
Interface SegregationAdapter, role interfaces, Facade
Dependency InversionFactory Method, Abstract Factory, dependency injection
GoF chapter 1: program to an interfaceAlmost all of them
GoF chapter 1: composition over inheritanceStrategy, 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 toMove
Switch statements on a type codeStrategy, State, polymorphismReplace Conditional with Polymorphism
Long Method with several phasesTemplate Method, StrategyExtract Method, then lift to a hook
Divergent ChangeFacade plus separate modulesExtract Class
Shotgun SurgeryMove behaviour to one place (Observer, Mediator)Move Method
Feature EnvyMove the method to the data's classMove Method
Duplicate Code across subclassesTemplate MethodPull Up Method
Primitive ObsessionValue Object, StateReplace Data Value with Object
Speculative GeneralityRemove the patternInline Class, Collapse Hierarchy
Long Parameter List / telescoping constructorsBuilder, functional optionsIntroduce Parameter Object
Object creation scattered with new and branchesFactory MethodReplace Constructor with Factory Method
Hard-coded dependency on a concrete classDependency injectionExtract 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.

text
     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 else

Criticism ​

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 featureGoF 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."

SymptomExampleCostFix
Interface with one implementation, never swappedUserRepositoryInterface plus UserRepository for a single databaseTwo files for one idea; jump-to-definition lands on the interfaceDelete the interface until a second implementation or a test needs it
Factory of factoriesAbstractNotifierFactoryProviderNames longer than the logicUse a plain constructor
Singleton for convenienceGlobal Config::getInstance()Hidden dependency, hard testsPass it in; let the container own lifetime
Strategy for one ruleClass StandardDiscount with an interfaceIndirection with no variationA function
Visitor on a hierarchy that changes weeklyAdding a class edits every visitorRigidityUse a switch or polymorphism
Patterns as a hiring or review checklist"Where is your Factory?"Pattern count becomes the metricReview for problem and consequences
text
     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 then

Modern 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).

PatternGoPHP (8.4)Verdict
SingletonPackage-level variable or sync.Once; no class needed$this->app->singleton(...) in the container; a static getInstance is a smellTrivial in both; avoid hand-made
Factory MethodNewX(...) function, registry like sql.RegisterContainer binding closure, static named constructorTrivial, still everywhere
Abstract FactoryA struct of constructor functions or one interfaceManager classes that return a driver familyRare
BuilderFunctional options or a struct literalNamed arguments; the query builder is a real fluent builderIdiom in Go, Trivial in PHP for small objects
PrototypeAssignment copies a struct by valueclone keywordTrivial
AdapterA small wrapper struct; http.HandlerFunc adapts a function to HandlerA class implementing a contract and wrapping a vendor SDKStill useful (anti-corruption)
BridgeAn interface field in a structConstructor-injected interfaceRare as a named pattern; used without a name
CompositeA struct holding a slice of the same interfaceSame; Laravel collections, nested form componentsStill useful for trees
DecoratorWrap an interface; io.Reader, middlewareWrap a contract; cache and logging decoratorsStill useful, central
FacadeThe package's exported APIA service class (not Laravel's static facades)Trivial in Go, still useful in PHP
FlyweightShare immutable values and intern strings by handShare immutable value objectsRare
ProxyWrapper types, generated clients (gRPC)Laravel facades, lazy objects, generated proxiesStill useful
Chain of Responsibilityhttp.Handler middlewareMiddleware, PipelineStill useful, central
CommandA function value or a struct with RunJobs, Artisan commands, form actionsIdiom in Go, Still useful in PHP (queued jobs)
InterpreterRare: parse and evaluate for DSLsRare: Blade, validation rule strings are mini-languagesRare
Iteratorrange; since Go 1.23 the iter package and range-over-funcforeach, Iterator, generators with yield, LazyCollectionTrivial in both
MediatorChannels and select, an event busEvents, command busStill useful
MementoCopy the struct, snapshot to a byte sliceSerialisation, event-sourcing snapshotsRare, but undo and snapshots need it
ObserverCallbacks, channelsEvents and listeners, Eloquent observersIdiom in Go, Trivial in Laravel
StateA state function, or a type with switchBacked enum plus match, or state classesStill useful, often an enum
StrategyA function type or a small interface (sort.Interface)Closures, contracts, driversTrivial in both: pass a function
Template MethodNo inheritance: pass funcs or use an interface; sort.SortAbstract base class, Laravel handle() hooksIdiom in Go, still useful in PHP
Visitorswitch v := x.(type)match on instanceof, double dispatch only for stable hierarchiesTrivial 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 13Go standard libraryService containerFactory + Dependency InjectionFacades (Cache::get)Proxy via __callStatic to a container objectPipeline, HTTP middlewareChain of ResponsibilityEvents and listenersObserverEloquent modelsActive Record (PoEAA)Query builder DB::table()->where()Fluent BuilderCache, Queue, Mail drivers + ManagersStrategy + Factoryio.Reader wrappers (LimitReader, TeeReader)Decorator / Adapterhttp.Handler and middlewareDecorator chain, Chain of Responsibilitysort.Interface, sort.ReverseStrategy (+ Template Method skeleton)context.WithCancel / WithValueChain of wrapped parentsdatabase/sql Register + OpenFactory registryFunctional optionsIdiom that replaces Builder

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 featurePatternEvidence (source read)
Service container (bind, singleton, contextual binding)Factory Method plus Dependency Injection; Singleton lifetimeLaravel 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\PipelineChain of Responsibilitysend(), through(), then() builds the chain with array_reduce in Pipeline.php
HTTP middlewareChain of Responsibility, Decorator-shapedDocs: "a series of 'layers' HTTP requests must pass through"
Events and listenersObserverDocs: "Laravel's events provide a simple observer pattern implementation"
Eloquent modelsActive 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 BuilderDocs: "convenient, fluent interface to creating and running database queries"
Cache, Queue, Mail, Filesystem drivers with CacheManagerStrategy chosen by a factory (the Manager)Manager::driver(), createDriver() with customCreators for Cache::extend
Macroable (Collection::macro)Open class / extension object, "decorator-ish" at bestMacroable::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)CommandThe job object carries a request to be run later
Collections (map, filter)Iterator plus fluent pipelineDocs: 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 libraryPatternWhat to read
io.LimitReader, io.TeeReader, io.MultiReader, io.NopCloserDecorator and Adapter around io.Readerpkg.go.dev/io: "TeeReader returns a Reader that writes to w what it reads from r."
http.Handler, http.HandlerFunc, http.StripPrefix, http.TimeoutHandlerAdapter (func to interface), Decorator chainpkg.go.dev/net/http: StripPrefix(prefix string, h Handler) Handler
sort.Interface (Len, Less, Swap), sort.ReverseStrategy (ordering) inside a fixed algorithm (Template Method flavour); Reverse is a decoratorpkg.go.dev/sort
context.Context with WithCancel, WithValueA chain of wrapped parentspkg.go.dev/context: "A Context carries a deadline, a cancellation signal, and other values across API boundaries."
database/sql Register and OpenFactory registryDrivers register in init()
Functional options (many third-party packages, not the stdlib)Idiom replacing BuilderPike'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.

go
// 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.

go
// 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.

go
// 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:

go
// 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:

go
// 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
<?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
<?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
<?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 writePattern behind itWhere the plumbing lives
app(Notifier::class) or constructor injectionFactory Method + DIContainer
Cache::remember(...)Proxy to the cache binding, Strategy for the storeFacade, CacheManager
Event::listen, #[ObservedBy]ObserverDispatcher, Eloquent events
Route::middleware(...)Chain of ResponsibilityHTTP kernel, Pipeline
dispatch(new Job(...))CommandQueue
Order::where(...)->first()Active Record + fluent BuilderEloquent, query builder

PHP idioms that remove small patterns:

php
<?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:

sql
-- $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 variesCandidatesCheapest first
Which class gets createdFactory Method, Abstract Factory, PrototypeA constructor function
How an object is configuredBuilderFunctional options, named arguments
The algorithmStrategy, Template MethodA function parameter
Behaviour that depends on stateStateA switch on an enum
Optional extra behaviour stacked in any orderDecorator, Chain of ResponsibilityA wrapper function
Incompatible interfaceAdapter, FacadeA small wrapper type
Who is notifiedObserver, MediatorA callback list
Operation on a tree of typesComposite, VisitorA recursive function
Request to queue, retry, undoCommand, MementoA job class
text
     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 ​

FamilyYou gainYou payTypical failure
CreationalCallers do not know concrete classes; creation is testableA new type or registry; indirection when readingFactory of factories
StructuralReuse and flexible assembly without editing old codeMany small objects; stack traces through wrappersWrapper that must forward 20 methods
BehavioralVariation behind a stable interface; loose couplingControl flow becomes hard to traceObservers that trigger observers
ConcurrencyThroughput and isolationOrdering, deadlock, shutdown complexityUnbounded queues
EnterpriseA place for persistence and use-case codeMapping layers, magicActive Record models with 3,000 lines
ArchitecturalWhole-system qualitiesHard to change laterLayers that leak
MessagingDecoupling in time and spaceEventual consistency, duplicatesMissing idempotency

Solving the classic problems ​

Classic problem: learning patterns without applying them blindly Important ​

ApproachHowAdvantageCost
Problem-first readingStart from a smell in your code, find the pattern in the catalogueYou learn the consequences with a real caseSlower than reading the book cover to cover
KataWrite the same small problem twice: plain and with the patternYou feel the billNeeds discipline
Read real codeOpen io, net/http, Laravel's Pipeline.php and name what you seeKnown uses are the best teachersNeeds the vocabulary first (this page)
Review checklistsAsk "which problem?" and "what are the consequences?" in every PRStops pattern-itisNeeds team buy-in
Refactoring to PatternsLet the smell appear, refactor in small stepsPatterns arrive when neededNeeds 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 ​

SituationRecommendedExtra techniqueReason
One rule today, no second in sightNo patternKeep it a plain functionIndirection must be paid for by variation
Two or three alternatives that growStrategyFunction type in Go, contract in PHPBehind one interface the call site stays stable
Cross-cutting concern around a call (log, retry, cache)Decorator or middlewareChain with Chain(h, mws...) or PipelineOrder is explicit and composable
Tangled new calls and driver switchFactory MethodRegistry in Go, container binding in LaravelOne place knows the concrete class
Many optional settingsBuilder idiomFunctional options, named argumentsNo telescoping constructors
An object with a life cycle (draft, paid, shipped)StateEnum plus match firstA closed set rarely needs a class per state
React to something that happenedObserverEvents in Laravel, callbacks or channels in GoPublisher does not know subscribers
Third-party API that will changeAdapterOwn interface in your domainProtects the rest of the code
Complicated subsystem, many callersFacadeA service class per use caseOne entry point per actor
Persistence of the domainRepository or Active RecordSee Data persistencePick by domain complexity
Cross-process coordinationNot a GoF patternOutbox, Saga, messagingThe 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 concernPatternWhy
Billing calls InventoryFacade on Inventory, interface in BillingBilling does not know Inventory's models
Reaction to OrderPlacedObserver via an in-process event busSame transaction, easy to test
Reports read ordersRepository or query object per moduleOnly 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.

text
     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 messages

Distributed 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 levelWhat breaks in a distributed setting
SingletonOne per process is not one per cluster (a "singleton" job runs on every pod)
ObserverDelivery is no longer reliable or ordered
Chain of ResponsibilityA handler may time out or be unavailable
MementoA snapshot must survive restarts and be versioned
CommandMust be idempotent to be retried safely

Scaling path: 1×, 10×, 100× ​

LoadWhat 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).

  1. Run the three families.

    text
    go 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 observer

    Expected: the output in the comments of each file. Add a push notifier by calling Register once; New does not change.

  2. Break the Decorator order. In structural, swap logging, requireKey for requireKey, logging. Predict which requests log before running. (Answer: the forbidden request no longer logs, because requireKey is now outermost.)

  3. Find patterns in the standard library.

    text
    go doc io.TeeReader
    go doc net/http.StripPrefix
    go doc sort.Reverse
    go doc context.WithValue

    For each, write one line: which GoF pattern, and which interface it wraps.

  4. Find them in Laravel. In a Laravel 13 project: grep -n "array_reduce" vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php and read carry(); 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.

  5. Refactor toward a pattern. Take this plain function and extract a Strategy only when the second rule exists:

    text
    func 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 apply Discount func(int) int from behavioral/main.go.

  6. 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 ​

BeliefReality
Patterns are reusable codeThey are descriptions; code is written per language and problem
The GoF book is the only pattern catalogueIt is one catalogue; PoEAA, EIP, POSA, DDD and PLoP collections exist
There are 23 patternsThere are 23 GoF patterns; thousands across catalogues
Patterns only work in OO languagesAlexander's came from buildings; Go uses them with interfaces and functions
Using more patterns means better designEach pattern is a cost; use the smallest that solves the problem
Singleton is a good way to share stateIt hides a dependency; let the container or main own lifetime
Laravel facades are the Facade patternThey are static proxies to container objects
Active Record is bad and Data Mapper is goodEach fits different domains; trade-offs are on Data persistence
Norvig showed patterns are obsoleteHe showed 16 of 23 are simpler with the right language features, and endorsed patterns as vocabulary
Family names tell you when to use a patternThey group by purpose; choose by the problem that hurts
Patterns replace principlesPrinciples judge a design; patterns offer shapes
A pattern name in the class name makes the code betterOnly if it carries meaning; ManagerFactoryHelper does not

Cheat sheet ​

TopicRemember
OriginAlexander 1977 (253 patterns) to Beck and Cunningham 1987 to GoF 1994
GoF counts23 patterns: 5 creational, 7 structural, 11 behavioral
TemplateName, Intent, Motivation, Applicability, Structure, Participants, Collaborations, Consequences, Implementation, Known uses, Related
Read orderIntent, Applicability, Consequences first; Structure last
NotA library, a goal, copy-paste code
Idiom vs patternIdioms are language-specific (functional options); patterns are design-level
Principle vs patternPrinciples judge; patterns propose
SmellStart from the pain; refactor toward the pattern (Kerievsky)
Norvig16 of 23 simpler with first-class functions, types, macros, modules
GoSmall interfaces, composition, functions: Strategy, Command, Visitor shrink; Decorator and Chain stay
PHP / LaravelContainer = factory + DI, Pipeline = Chain, Events = Observer, Eloquent = Active Record, drivers = Strategy
Beyond GoFConcurrency, PoEAA, architecture, messaging patterns
Anti-patternPattern-itis: interface with one implementation, factory of factories

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Design patternA named, documented solution to a recurring design problem, with its consequences
Pattern languageA set of patterns that refer to each other and are used in a sequence (Alexander)
CatalogueA collection of patterns in one template (GoF, PoEAA, EIP)
GoF (Gang of Four)Gamma, Helm, Johnson, Vlissides; authors of the 1994 Design Patterns
Creational patternPattern about object creation
Structural patternPattern about assembling objects into larger structures
Behavioral patternPattern about algorithms and responsibilities between objects
Concurrency patternPattern for coordinating threads, goroutines or processes
Enterprise application patternPattern from Fowler's PoEAA for persistence, domain logic and presentation
Architectural patternPattern for the structure of a whole system
Messaging and integration patternPattern from Hohpe and Woolf's EIP for communication between processes
PLoPPattern Languages of Programs, the conference run by the Hillside Group
Hillside GroupThe community that promotes patterns and runs PLoP
IntentOne sentence saying what problem a pattern solves
MotivationA concrete scenario that shows the problem
ApplicabilityWhen to use the pattern
ParticipantsThe roles (classes or functions) in a pattern
ConsequencesThe trade-offs of applying the pattern
Known usesReal systems where the pattern appears
IdiomA language-specific way to write a small construct
Functional optionsGo idiom: option functions passed to a constructor (Pike, 2014)
PrincipleA rule used to judge designs, such as SOLID
Code smellA symptom in code that suggests a design problem
Refactoring to PatternsKerievsky's method: reach a pattern by small refactorings from a smell
Pattern-itisUsing patterns without a problem to solve
Speculative GeneralitySmell: abstractions added for needs that do not exist yet
Invisible / informal / formal patternNorvig's levels: built into the language, described in prose, or implemented as reusable code
Active RecordFowler: an object that wraps a row, handles DB access and adds domain logic; Eloquent
Service containerLaravel's dependency injection container; a factory and registry
Facade (Laravel)Static-looking class that proxies to a container object via __callStatic
PipelineLaravel's chain of pipes, each receiving a payload and a $next closure
ManagerLaravel class that creates a driver by name (CacheManager)
MacroableLaravel trait that lets you add methods to a class at runtime
io.Reader decoratorGo wrapper type implementing io.Reader around another reader
http.Handler middlewareA function that takes a handler and returns a handler

References ​

Built by Morteza Negahi