Skip to main content

What Are Design Patterns? — History & Classification

Editorial

Introduction

Design problems repeat. You want to create objects without your code naming their exact classes. You want to add behavior to an object without editing its class. You want objects to react to each other's changes without knowing each other. Engineers met these problems again and again, and the good solutions turned out to look alike.

A design pattern names one of those problems and the shape of a solution that works for it. It is not code to copy. It is a blueprint: the classes involved, what each one is responsible for, and how they work together. You adapt it to your own domain, the way an arch serves a bridge, a doorway and a cathedral without being any one of them.

Here you will see where patterns came from, what makes something a pattern, how the classic 23 are sorted, and when to use one and when not to. It builds on Foundations - Low Level Design: classes and interfaces, composition, and the SOLID principles. Every lesson after this one takes one pattern.

Where Design Patterns Came From

The idea began with buildings. In 1977 the architect Christopher Alexander and his colleagues published A Pattern Language with Oxford University Press: more than 250 patterns for towns, buildings and rooms. Each pattern answers a design problem, the kind of question the book's publisher lists as "How high should a window sill be? How many stories should a building have?", and each one consists of a problem statement, a discussion of the problem with an illustration, and a solution. Pattern 159, for example, is called LIGHT ON TWO SIDES OF EVERY ROOM.

In 1987 Kent Beck and Ward Cunningham tried the idea on software. In a report for a workshop at the OOPSLA-87 conference they proposed "a very small pattern language for designing Smalltalk windows": five patterns, among them Window Per Task and Short Menus.

On 31 October 1994, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published Design Patterns: Elements of Reusable Object-Oriented Software with Addison-Wesley. It describes 23 patterns, each with code in C++ or Smalltalk, and its four authors became known as the Gang of Four. Their first chapter quotes Alexander's own definition of a pattern: "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice".

What Makes Something a Design Pattern

The book gives every pattern four elements.

1. A name

A word or two that stands for the whole design: the problem, the solution and the consequences. In the book's words, "Naming a pattern immediately increases our design vocabulary." When you say "a Decorator here", another developer pictures the classes and the calls without a long explanation.

2. The problem

When to apply the pattern: the design problem and its context. For example: how can code create objects without naming their concrete classes, so that adding a new kind of object does not change the code that uses them? Reach for a pattern only when you have its problem.

3. The solution

The classes and objects that make up the design, what each is responsible for, and how they work together. It is not one concrete design, because the same pattern fits many situations: a factory for vehicles and a factory for documents look different but have the same shape.

4. The consequences

"The consequences are the results and trade-offs of applying the pattern." Every pattern costs something. Singleton gives every caller one shared instance, and with it global state that every test shares. Factory Method keeps code free of concrete classes, but you may have to write a new creator subclass just to make one new kind of product. Knowing the costs is what separates using a pattern well from overusing it.

Two Ways to Sort the 23 Patterns

The book sorts its patterns by two criteria. The first is purpose, what a pattern does:

  • Creational patterns are about making objects. They take creation out of the code that uses the objects, so a new kind of object does not change that code.
  • Structural patterns are about putting classes and objects together into larger structures: adapting an interface, wrapping an object, sharing objects, building trees.
  • Behavioral patterns are about how objects work together and share the work: who handles a request, who hears about a change, which algorithm runs.

The second is scope. A class pattern works through inheritance, so its relationships are fixed when the code is compiled. An object pattern works through links between objects, which can change while the program runs. Most patterns have object scope. Only four are class patterns: Factory Method, Adapter in its class form, Interpreter and Template Method. Adapter comes in both forms: a class adapter inherits from the class it adapts, while an object adapter holds an instance of it.

Creational patterns: how objects are made

PatternWhat it doesScope
SingletonMake sure a class has only one instance, and give everyone one way to reach itObject
Factory MethodLet a subclass decide which class to createClass
Abstract FactoryCreate families of related objects without naming their concrete classesObject
BuilderBuild a complex object step by step, so the same steps can build different resultsObject
PrototypeCreate new objects by copying an existing oneObject

Structural patterns: how objects are put together

PatternWhat it doesScope
AdapterTurn one interface into the one a client expectsClass and object
FacadeGive a subsystem one simpler interfaceObject
DecoratorAdd responsibilities to one object at run time, without subclassingObject
CompositeBuild part-whole trees, and treat one object and a group of them the same wayObject
ProxyPut a stand-in in front of an object to control access to itObject
BridgeSplit an abstraction from its implementation, so the two can change apartObject
FlyweightShare small objects, so that very many of them stay cheapObject

Behavioral patterns: how objects share the work

PatternWhat it doesScope
StrategyMake a family of algorithms interchangeableObject
ObserverWhen one object changes, tell every object that depends on itObject
CommandTurn a request into an object, so it can be queued, logged or undoneObject
StateLet an object change its behavior when its state changesObject
Template MethodFix the steps of an algorithm in a base class, and let subclasses fill in some of themClass
IteratorGo through a collection's elements one by one without seeing how it stores themObject
Chain of ResponsibilityPass a request along a chain of handlers until one handles itObject
MediatorLet objects talk through one object instead of to each otherObject
MementoSave an object's state outside it without breaking its encapsulation, so it can be restoredObject
VisitorAdd an operation to a class hierarchy without changing its classesObject
InterpreterRepresent the grammar of a small language as classes, and evaluate its sentencesClass

The 23 Patterns on One Map

The same 23 patterns on one map, purpose across and scope down, each with a picture of its idea.

The 23 design patterns of Gamma, Helm, Johnson and Vlissides (the Gang of Four, 1994) on one map, as their book sorts them: by purpose in three columns and by scope in two bands. Patterns began with the architect Christopher Alexander's book on buildings (1977). Creational patterns, how objects are made: Factory Method in the class band; Abstract Factory, Builder, Prototype and Singleton in the object band. Structural patterns, how objects are put together: Adapter in both bands (a class adapter inherits what it adapts, an object adapter holds it); Bridge, Composite, Decorator, Facade, Flyweight and Proxy in the object band. Behavioral patterns, how objects share the work: Interpreter and Template Method in the class band; Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy and Visitor in the object band. Class scope means the pattern works through inheritance, fixed when the code is compiled; object scope means it works through links between objects that can change while the program runs. Each pattern is drawn as a small picture of its idea. Below, the four elements every pattern has: a name (one word for the whole design), the problem (when to apply it), the solution (the classes and how they work together) and the consequences (the results and the trade-offs). Takeaway: a pattern is a blueprint you adapt to your problem, not code you copy.

Check Yourself: Which Pattern Fits?

Each question gives a situation. Pick the pattern built for it; each answer says why, and which lesson to read next.

Which Pattern Fits?

1 / 12

Multiple choice

Every part of an app must read its settings from one configuration object, and nothing may create a second one. Which pattern fits?

How Patterns Connect to What You Already Know

The book names two principles behind its patterns. The first is "Program to an interface, not an implementation." Code that holds an interface can be handed any class that implements it. The second is "Favor object composition over class inheritance." Behavior assembled from objects can change while the program runs; behavior inherited from a parent class is fixed when the code is compiled. Most patterns use both.

The principles from Foundations - Low Level Design show up in the patterns too:

PrinciplePatterns that put it to work
S — Single Responsibility PrincipleFactory Method moves creating objects out of the code that uses them; Observer keeps handling an event apart from raising it
O — Open/Closed PrincipleStrategy, Observer and Decorator let you add a behavior as a new class, without editing the old ones
L — Liskov Substitution PrincipleStrategy, State and Factory Method work only if every subclass can stand in for its parent
I — Interface Segregation PrincipleFacade gives a client the few operations it needs instead of a whole subsystem
D — Dependency Inversion PrincipleAbstract Factory, Factory Method and Strategy make code depend on interfaces, not on concrete classes
Composition Over InheritanceDecorator, Strategy and Bridge build behavior out of objects instead of subclasses

You have already used two patterns. In Refactoring: Switch-Case → Strategy Pattern you turned a switch over types into Strategy objects. In Refactoring: Tight Coupling → Dependency Injection you passed a class its dependencies through its constructor. That is Dependency Injection, which is not one of the book's 23: Martin Fowler named it in January 2004, writing "we settled on the name Dependency Injection".

Patterns and the Language You Write In

The book's preface says its patterns need no special language features: "All can be implemented in standard object-oriented languages, though they might take a little more work than ad hoc solutions." Languages still differ in how much of a pattern you write yourself.

  • Python builds Iterator into its for loop. The loop asks the collection for an iterator and takes items from it until it runs out; as Python's glossary puts it, "The for statement does that automatically for you".
  • Where a function is a value you can pass around, a Strategy can be a function instead of a class.
  • In 1996 Peter Norvig compared the book's patterns with the Lisp and Dylan languages and found that "16 of 23 patterns have qualitatively simpler implementation in Lisp or Dylan than in C++ for at least some uses of each pattern".

So learn each pattern as a problem and the shape of a solution. How much code it takes depends on your language.

When to Use Design Patterns

Use a pattern when:

  • You recognize a problem a pattern is built for. A switch over object types that decides which class to create is the Factory Method problem. Several objects that must react to one object's change is the Observer problem. You learn to see these problems by working through them, and each pattern lesson gives its problem a worked example.
  • A change is coming that you already know about. If the system will add new payment methods, notification channels or vehicle types, Strategy, Observer and Factory Method let you add each one as a new class.
  • A team shares the code. A pattern's name is a shared word: "this is a Builder" says more than a paragraph.
  • You are designing in an interview. This course's advice: name the pattern you use and say which problem it solves in this design. A pattern with a reason shows judgment; a pattern without one is extra structure.

When Not to Use Design Patterns

A pattern used where it does not belong costs as much as a missing one. Hold back when:

  • It is too early. Don't add a Factory Method when a plain constructor works and no other kind of object is coming. YAGNI — You Aren't Gonna Need It applies to patterns too.
  • Patterns are stacked for their own sake. Decorator, Proxy, Adapter and Facade around a feature that one well-designed class could handle is over-engineering: each pattern adds a layer and at least one more class or interface.
  • It is the wrong pattern. Choosing Singleton because a class is handy to reach from everywhere solves convenience, not design. Passing the object in where it is needed (Dependency Injection) usually solves the real problem and keeps the class easy to test.
  • The count becomes the goal. "My design uses eight patterns" is not an achievement. The smallest structure that solves the problem is.

Use the right pattern for the right problem, and only when the problem is worth the extra structure.

Common Mistakes

1. Copying a pattern's code instead of adapting it

Mistake: pasting a pattern example from the web without changing its classes, names and calls to fit your domain.

Why it's wrong: the book describes an abstract design, not finished code. A creator in a document system makes PdfDocument and HtmlDocument; in a shop it makes PhysicalProduct and DigitalProduct. The shape is the same; the code is not.

Fix: understand the pattern's intent first. Then map each participant (Creator, Product, Subject, Observer) onto your own domain's nouns and verbs.

2. Using a pattern you don't need

Mistake: adding an Abstract Factory for one kind of object, with no family of products and no variation in sight.

Why it's wrong: every pattern adds interfaces, classes and layers to read through. Without the problem, you pay the cost and get nothing back.

Fix: start with the simplest design that works, and bring in a pattern when you feel the pain it removes: when adding one new type means editing five classes, that is when Factory Method earns its place.

3. Ignoring the consequences

Mistake: picking Singleton for easy access from everywhere without counting what it costs.

Why it's wrong: one shared instance is global state that every part of the program and every test shares, and code that fetches it directly cannot be handed a stand-in in a test.

Fix: for every pattern, read When Not to Use as closely as When to Use. A pattern that solves one problem and creates three new ones is not a good trade.

Key Takeaways

  • A design pattern names a recurring design problem and the shape of a solution to it. You adapt it; you don't copy it.
  • The idea came from Christopher Alexander's A Pattern Language (1977). Kent Beck and Ward Cunningham tried it on software in 1987, and the Gang of Four's book (1994) gave software its 23 classic patterns.
  • Every pattern has four elements: a name, a problem, a solution and consequences.
  • The 23 are sorted by purpose (creational, structural, behavioral) and by scope (class or object). Most have object scope.
  • Patterns put principles to work: program to an interface, favor composition over inheritance, and the SOLID principles.
  • How much code a pattern takes depends on the language, and some languages build a pattern in.
  • Use a pattern when you have its problem, and only when the problem is worth the extra structure.