Pattern families (GoF)

GoF
Gang of Four

Junior Frequently asked 4 min

On this page

The question

What design patterns do you know, and where have you used them?

30-second answer

Group them by family, then give one you really used per family. Creational: Builder for an immutable request. Structural: Decorator around a repository, or the proxy behind @Transactional. Behavioral: Strategy to replace a switch on payment type. A pattern is a named solution to a recurring design problem, so name the problem each one solved.

Understand it

The 23 GoF patterns by family

Tap the parts

Select a part to see what it does.

Tap a family to see the question it answers, or tap the favorites to see which patterns come up most.

View as text

A map of the 23 patterns from the Gang of Four book, grouped into three panels, with 12 interview favorites marked by a star.

Creational, 5 patterns, about how objects are created: Singleton, Factory Method, Abstract Factory, Builder and Prototype. All but Prototype are starred.

Structural, 7 patterns, about how objects are composed: Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy. Adapter, Decorator, Facade and Proxy are starred.

Behavioral, 11 patterns, about how objects communicate: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method and Visitor. Chain of Responsibility, Observer, Strategy and Template Method are starred.

Interview favorites: the 12 starred patterns are the ones this track teaches, because Java and Spring use them daily.

A map of the 23 patterns from the Gang of Four book, grouped into three panels, with 12 interview favorites marked by a star.

Creational, 5 patterns, about how objects are created: Singleton, Factory Method, Abstract Factory, Builder and Prototype. All but Prototype are starred.

Structural, 7 patterns, about how objects are composed: Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy. Adapter, Decorator, Facade and Proxy are starred.

Behavioral, 11 patterns, about how objects communicate: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method and Visitor. Chain of Responsibility, Observer, Strategy and Template Method are starred.

Interview favorites: the 12 starred patterns are the ones this track teaches, because Java and Spring use them daily.

Takeaway: Name the family first: creational patterns create objects, structural patterns compose them, and behavioral patterns make them communicate. Twelve starred patterns come up most.

Which pattern family a problem belongs toAsk what needs to vary. If it is which object gets created, the family is creational. If it is how objects fit together, the family is structural. If it is how objects communicate, the family is behavioral.What varies?Which object iscreated:CreationalHow objects fittogether:StructuralHow objectscommunicate:Behavioral
Which pattern family a problem belongs toAsk what needs to vary. If it is which object gets created, the family is creational. If it is how objects fit together, the family is structural. If it is how objects communicate, the family is behavioral.What varies?Which object iscreated:CreationalHow objects fittogether:StructuralHow objectscommunicate:Behavioral
Which family a problem belongs to

In code

// Creational: Builder assembles an immutable request.
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/orders"))
    .header("Accept", "application/json")
    .GET()
    .build();

// Structural: Decorator wraps a stream and adds buffering, same type.
InputStream in = new BufferedInputStream(new FileInputStream("orders.csv"));

// Behavioral: Strategy passes the sorting rule as an object.
names.sort(Comparator.comparing(String::length));
One pattern per family, from the JDK (Java Development Kit)
Three patterns from the JDK, one per familyThe builder of HttpRequest is a creational Builder. BufferedInputStream is a structural Decorator. Comparator passed to List sort is a behavioral Strategy.CreationalHttpRequest builderBuilderStructuralBufferedInputStreamDecoratorBehavioralComparator in sort()Strategy
Three patterns from the JDK, one per familyThe builder of HttpRequest is a creational Builder. BufferedInputStream is a structural Decorator. Comparator passed to List sort is a behavioral Strategy.CreationalHttpRequest builderBuilderStructuralBufferedInputStreamDecoratorBehavioralComparator in sort()Strategy
Three patterns from the JDK, one per family
List<String> names = List.of("ana", "ben");                       // static factory method
NumberFormat money = NumberFormat.getCurrencyInstance(Locale.US); // factory method: picks the subclass for you
Runtime runtime = Runtime.getRuntime();                           // singleton: one per JVM (Java Virtual Machine)
Creational patterns in the JDK: factory methods and a singleton
List<Integer> view = Arrays.asList(1, 2, 3);                    // Adapter: an array seen as a List
List<Integer> readOnly = Collections.unmodifiableList(view);    // protection proxy: same interface, writes refused
Iterator<Integer> it = readOnly.iterator();                     // Iterator: walk without knowing the structure
Structural and behavioral patterns in the JDK

Solve it

Name the pattern for three design requests

An interviewer describes three needs and asks which pattern fits each: (a) dashboards must refresh when a stock price changes; (b) a vendor SDK (software development kit) must fit your PaymentGateway interface; (c) an HTTP request has ten optional settings.

  1. Ask what varies. Creating objects points to a creational pattern, fitting or wrapping objects to a structural one, and who reacts or decides at runtime to a behavioral one.
  2. (a) Who reacts. Many objects react to one change without the source knowing them: behavioral, Observer.
  3. (b) Fitting a shape. Your code expects one interface and the SDK offers another: structural, Adapter.
  4. (c) Creating step by step. Many optional parts and an immutable result: creational, Builder.
  5. Check the answer aloud. Name the pattern, its family and the problem it removes, then give a JDK or Spring example.
// (a) Observer: the price feed knows only the listener interface
interface PriceListener { void onPrice(String symbol, BigDecimal price); }

// (b) Adapter: your interface on the outside, the vendor SDK on the inside
class VendorPaymentAdapter implements PaymentGateway {
    private final VendorSdk sdk;
    VendorPaymentAdapter(VendorSdk sdk) { this.sdk = sdk; }
    public Receipt charge(Money amount) { return Receipt.from(sdk.makePayment(amount.cents())); }
}

// (c) Builder: named optional settings, one immutable result
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/quotes"))
    .timeout(Duration.ofSeconds(5))
    .header("Accept", "application/json")
    .build();
The three answers as code skeletons

How to answer

  • The Gang of Four book lists 23 patterns in three families.
  • Answer with a problem you had, the pattern you chose and what it cost.
  • Spring already uses many of them, such as Singleton, Proxy, Template Method and Observer.
  • A pattern is a shared vocabulary, not a library you import.

Common mistakes

  • Reciting pattern names with no example of when you used one.
  • Treating more patterns as better design; each one adds indirection you must justify.

Follow-up questions

What is the difference between creational, structural and behavioral patterns?

They answer different questions. Creational patterns decide how objects get created, so callers do not name concrete classes. Structural patterns decide how objects are composed into larger structures. Behavioral patterns decide how objects communicate and share responsibilities. Asking what needs to vary usually tells you which family to look in.

  • Creational (5): Singleton, Factory Method, Abstract Factory, Builder, Prototype.
  • Structural (7): Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
  • Behavioral (11): Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor.

See it in the infographic: The 23 GoF patterns by family

Which design patterns can you point to in the JDK and in Spring?

The JDK has Builder in HttpRequest.newBuilder(), Decorator in BufferedInputStream, Adapter in InputStreamReader, Strategy in Comparator and Iterator in every collection. Spring has Singleton-scoped beans, Proxy behind @Transactional, Template Method in OncePerRequestFilter, Observer in ApplicationEventPublisher and Chain of Responsibility in its filter chain.

  • Naming a real class shows you recognize a pattern outside a textbook.
  • Spring's default bean scope is one object per container, not a GoF Singleton class.
  • JdbcTemplate fixes the steps but takes callbacks, so it is a variation on Template Method.

See it in the infographic: The 23 GoF patterns by family

When should you not use a design pattern?

When the problem it solves is not there yet. A Strategy interface with one implementation, or a factory that only ever makes one class, adds indirection and gives nothing back. Start with plain code, then introduce the pattern when a second variation or a real need appears. YAGNI (You Aren't Gonna Need It) applies to patterns too.

  • Each pattern trades extra classes and indirection for a kind of flexibility.
  • Refactor toward a pattern when duplication or a change request shows the need.
  • A lambda or an enum is often enough in modern Java.

How is a design pattern different from an algorithm?

An algorithm is exact steps that solve a computation, and you can copy it as code. A pattern is a reusable design idea about how classes collaborate. You adapt it to your classes each time, so two Strategy implementations can share no code at all.

Who are the Gang of Four?

Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, who wrote "Design Patterns" in 1994. The book catalogs 23 object-oriented patterns. Its examples are in C++ and Smalltalk, and some patterns are simpler in modern Java: a lambda often replaces a one-method Strategy class.

Check yourself

1. You must add retry and logging around a repository without editing it, keeping the same interface. Which family holds the pattern you want?
Show answers
  • Structural: Correct. Decorator wraps an object and keeps its interface, so this composes objects.
  • Creational: Incorrect. Nothing here changes how the repository is created.
  • Behavioral: Incorrect. Those patterns share responsibilities between collaborators; this adds a wrapper around one object.
2. How many patterns does the Gang of Four book catalog, and how are they split across the families?
Show answers
  • 23, split into 5 creational, 7 structural and 11 behavioral: Correct. That is the book's catalog, and the map draws all 23.
  • 12, split evenly with 4 in each family: Incorrect. Twelve is how many this track teaches, not how many the book lists.
  • 30, split evenly with 10 in each family: Incorrect. The book lists 23 patterns, and the families are not equal in size.