All 23 GoF Patterns: Overview and Classification

A map of the 23 Gang of Four design patterns: the three categories, class versus object scope, one-line intents, JDK examples, and how to choose between patterns that look alike.

On this page

Simple definition#

The Gang of Four (GoF) catalogue is the set of 23 object-oriented design patterns published in Design Patterns: Elements of Reusable Object-Oriented Software (1994). The book sorts them along two axes:

  • Purpose — what the pattern does: creational, structural or behavioral.
  • Scope — whether the relationships are fixed at compile time through inheritance (class scope) or set up at runtime through composition (object scope).

This page is the map. Each pattern gets its own article; patterns not yet written are listed as plain text so that no page pretends to be finished.

Why a classification matters#

A classification turns 23 unrelated names into a few questions you can ask about a design:

  1. Is the difficulty creating objects, wiring objects together, or distributing behaviour among them?
  2. Should the variation be fixed when the code is compiled, or chosen while the program runs?

Answering those two questions usually narrows the candidates to two or three patterns. The comparison pages then help you choose between them.

The three categories#

GoF patterns by purpose
flowchart LR
    GoF["23 GoF patterns"]
    GoF --> C["Creational (5)<br/>how objects are created"]
    GoF --> S["Structural (7)<br/>how objects are composed"]
    GoF --> B["Behavioral (11)<br/>how objects share responsibility"]
    C --> C1["Singleton · Factory Method · Abstract Factory<br/>Builder · Prototype"]
    S --> S1["Adapter · Bridge · Composite · Decorator<br/>Facade · Flyweight · Proxy"]
    B --> B1["Chain of Responsibility · Command · Interpreter<br/>Iterator · Mediator · Memento · Observer<br/>State · Strategy · Template Method · Visitor"]

Creational patterns#

Creational patterns hide which concrete class is instantiated and how. Client code then depends on abstractions instead of new ConcreteClass().

#PatternIntent in one lineScopeIn the JDK or Spring
1SingletonEnsure a class has one instance and provide a global access point to it.ObjectRuntime.getRuntime()
2Factory MethodLet subclasses decide which class to instantiate.ClassCollection.iterator() (each collection creates its own iterator)
3Abstract FactoryCreate families of related objects without naming their concrete classes.Objectjavax.xml.parsers.DocumentBuilderFactory
4BuilderSeparate the construction of a complex object from its representation.ObjectStringBuilder, HttpRequest.newBuilder()
5PrototypeCreate new objects by copying an existing instance.ObjectObject.clone() (with well-known caveats)

Structural patterns#

Structural patterns describe how objects are wired together. Several of them have the same shape — a class that holds a reference to another object — and differ only in intent.

#PatternIntent in one lineScopeIn the JDK or Spring
6AdapterConvert one interface into another that clients expect.Class or objectArrays.asList, InputStreamReader
7BridgeDecouple an abstraction from its implementation so both can vary.ObjectJDBC: DriverManager and Connection over vendor drivers
8CompositeTreat individual objects and groups of objects uniformly.ObjectAWT/Swing Container holding Components
9DecoratorAttach responsibilities to an object dynamically by wrapping it.ObjectBufferedInputStream, Collections.unmodifiableList
10FacadeProvide one simple interface to a complex subsystem.ObjectSpring’s JdbcTemplate over raw JDBC (resembles)
11FlyweightShare fine-grained objects to support large numbers efficiently.ObjectInteger.valueOf cache for −128…127
12ProxyProvide a placeholder that controls access to another object.Objectjava.lang.reflect.Proxy, Spring AOP proxies

Behavioral patterns#

Behavioral patterns are about algorithms and about who is responsible for what: who decides, who reacts, and where variation is plugged in.

#PatternIntent in one lineScopeIn the JDK or Spring
13Chain of ResponsibilityPass a request along a chain of handlers until one handles it.ObjectServlet FilterChain, Spring Security filter chain
14CommandEncapsulate a request as an object.ObjectRunnable, Callable
15InterpreterRepresent a grammar and interpret sentences in it.Classjava.util.regex.Pattern (internally), Spring Expression Language
16IteratorAccess elements sequentially without exposing the underlying structure.Objectjava.util.Iterator
17MediatorCentralise complex communication between objects in one object.ObjectNo clean JDK example; a dialog controller coordinating form widgets is the classic case
18MementoCapture and restore an object’s state without breaking encapsulation.ObjectUndo stacks in editors; rarely visible in library APIs
19ObserverNotify dependents automatically when an object changes.Objectjava.util.concurrent.Flow, Spring ApplicationEvent
20StateLet an object change behaviour when its internal state changes.ObjectCommon in workflow engines; no canonical JDK example
21StrategyDefine interchangeable algorithms behind one interface.ObjectComparator, Spring Security PasswordEncoder
22Template MethodDefine an algorithm’s skeleton and let subclasses fill in steps.Classjava.util.AbstractList, HttpServlet.service
23VisitorAdd operations to an object structure without changing its classes.Objectjava.nio.file.FileVisitor, javax.lang.model element visitors

Class scope versus object scope#

The scope axis is easy to overlook, but it is often the more useful one in practice.

ScopeMechanismFixed when?Patterns
ClassInheritanceCompile timeFactory Method, Adapter (class form), Interpreter, Template Method
ObjectComposition and delegationRuntimeThe other nineteen (and Adapter in its object form)

The proportion — four class-scope patterns against nineteen object-scope ones — illustrates the book’s advice to favour object composition over class inheritance. Several pairs of patterns solve the same problem with each mechanism:

  • Template Method (inheritance) and Strategy (composition) both let you vary steps of an algorithm.
  • Factory Method (inheritance) and Abstract Factory (composition) both hide which concrete class is created.
  • Class adapter and object adapter both translate interfaces.

How to choose: start from the problem#

The categories are useful for learning. When designing, it is faster to start from the symptom.

Symptom in the codeCandidate patterns
A growing switch or if chain selects behaviourStrategy, State, Command
A constructor with many optional parametersBuilder
Client code calls new on classes that vary by configuration or platformFactory Method, Abstract Factory
A third-party API does not match your interfaceAdapter
A complex subsystem leaks into every callerFacade
You need to add logging, caching or security around callsDecorator, Proxy
Objects are tightly coupled through many-to-many callsMediator, Observer
Tree structures where leaves and groups are handled differentlyComposite (often with Visitor or Iterator)
Undo or snapshots are neededMemento, Command
A request may be handled by one of several handlers in orderChain of Responsibility

Patterns that are easy to confuse#

Confused pairThe deciding question
Strategy vs StateDoes the client choose the behaviour (Strategy), or does the object switch behaviour itself as its state changes (State)?
Strategy vs Template MethodIs the variation plugged in through composition at runtime (Strategy) or fixed through subclassing (Template Method)?
Adapter vs Decorator vs Proxy vs FacadeDoes the wrapper translate an interface, add behaviour, control access, or simplify a subsystem? See the comparison.
Factory Method vs Abstract Factory vs simple factoryIs creation deferred to a subclass, delegated to a factory object that makes a family, or just centralised in one method? See the comparison.
Observer vs MediatorDo subjects broadcast to any number of observers, or does one mediator coordinate a known set of colleagues?
Command vs StrategyDoes the object represent a request to execute later (Command), or a way of doing something (Strategy)?
Composite vs DecoratorBoth use recursive composition. Composite aggregates many children; Decorator wraps exactly one object to add behaviour.

Patterns and modern Java#

Since the book was written in 1994, Java has gained features that change how several patterns are implemented — and occasionally whether you need a named class at all.

PatternModern Java alternative or simplification
Strategy, Command, ObserverA lambda or method reference implementing a functional interface
BuilderRecords with compact constructors cover simple value objects; builders still help with many optional fields
SingletonAn enum with one constant, or — better — one instance managed by a DI container
IteratorIterable plus the enhanced for loop, and streams
VisitorSealed interfaces with pattern matching for switch (Java 21) for closed hierarchies
PrototypeCopy constructors or static copy factories, avoiding Cloneable
Template MethodDefault methods in interfaces, or a Strategy passed as a lambda

Common mistakes#

  • Treating the catalogue as complete. Patterns such as Dependency Injection, Repository, Null Object and Specification are widely used but are not among the 23 GoF patterns.
  • Mixing up levels. Microservices, Saga and Circuit Breaker are architecture or distributed-systems patterns, not GoF patterns.
  • Using Singleton as a global variable. Singleton is the most criticised GoF pattern because it hides dependencies and shares state between tests. Prefer a single instance managed by Dependency Injection.

Interview questions and answers#

How many GoF patterns are there, and how are they classified? Twenty-three, in three categories by purpose: five creational, seven structural and eleven behavioral. They are also classified by scope — class patterns use inheritance and are fixed at compile time; object patterns use composition and can change at runtime.

Which GoF patterns use inheritance rather than composition? Factory Method, Template Method, Interpreter and the class form of Adapter.

Name a pattern from each category that you have used in the JDK. Creational: HttpRequest.newBuilder() (Builder). Structural: BufferedReader wrapping a Reader (Decorator). Behavioral: Comparator passed to List.sort (Strategy).

Is Dependency Injection a GoF pattern? No. It became popular later, through frameworks such as Spring and Martin Fowler’s 2004 article that named it. It is closely related to the Strategy pattern and to the Dependency Inversion Principle.

Summary#

  • The 23 GoF patterns are classified by purpose (creational, structural, behavioral) and by scope (class or object).
  • Only four patterns rely on inheritance; the catalogue as a whole favours composition.
  • Start from the symptom in your code, shortlist candidates, then decide using the patterns’ consequences.
  • Modern Java features make several patterns smaller, but the underlying problems remain.

References#