Suppose you are learning chess. At first you only know how each piece moves. After some games you start noticing recurring ideas: a fork, a pin, castling early to protect the king. Nobody invents these from scratch in every game. Players learn them once, give them names, and reuse them whenever a similar position appears.
Software design works the same way. After many years of building object-oriented systems, developers noticed that the same design problems kept coming back: "How do I make sure only one object of this class exists?", "How do I add features to an object without editing its class?", "How do I tell many objects when something changes?". Good solutions to these problems were also similar every time. These named, reusable solutions are called design patterns.
In this chapter we will understand what a design pattern is (and what it is not), where the idea came from, how the 23 classic patterns are organised, the design principles behind them, and we will write two small patterns you have probably already used without knowing their names. The next three chapters then cover the most important patterns one by one.
What Is a Design Pattern?
A design pattern is a general, reusable solution to a commonly occurring problem in software design, described in a way that can be applied in many different situations.
Three words in this definition matter:
General — a pattern is not tied to one project. The same Observer idea is used in a cricket score app, a stock market app and a GUI button.
Reusable — you reuse the idea, not the code. You will write the code again every time, adapted to your classes.
Design — patterns are about how classes and objects are arranged and how they talk to each other, not about small coding tricks or algorithms.
A pattern is a bit like a template for a solution. A recipe for "dal tadka" tells you the steps, but you still decide how much chilli to add. In the same way, a pattern tells you which roles exist (for example "Subject" and "Observer"), how they relate, and what the trade-offs are. You fill in the real classes.
What a Design Pattern Is Not
Thing | What it is | Example |
|---|---|---|
Design pattern | A reusable arrangement of classes and objects that solves a design problem | Observer, Strategy, Singleton |
Algorithm | A precise, step-by-step procedure that solves a computational problem | Binary search, Dijkstra's shortest path |
Library / framework | Ready-made code you call (library) or that calls your code (framework) | Java Collections, Spring |
Idiom | A low-level coding habit specific to one language | try-with-resources in Java, RAII in C++ |
Architectural pattern | A large-scale structure for a whole application | MVC, layered architecture, microservices |
Frameworks are usually built using many design patterns, which is one reason learning patterns makes frameworks easier to understand.
Where Did Design Patterns Come From?
The idea did not start in computing. The architect Christopher Alexander wrote A Pattern Language (1977), describing recurring solutions in buildings and towns, such as "a window place" or "a light on two sides of every room". He said each pattern describes a problem that occurs again and again, and the core of its solution, so that you can use the solution many times without ever doing it exactly the same way twice.
Software developers borrowed this idea. The book that made it famous is:
Design Patterns: Elements of Reusable Object-Oriented Software (1994) by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.
The four authors are nicknamed the Gang of Four (GoF), so the 23 patterns in their book are called the GoF patterns. Their examples were in C++ and Smalltalk, but the ideas apply to any object-oriented language, including Java, C#, Python and Kotlin. When an interviewer says "design patterns", they almost always mean these 23.
The Four Essential Elements of a Pattern
The GoF book describes every pattern using the same structure. The four essential parts are:
Element | Question it answers |
|---|---|
Name | What do we call it? A shared name lets a team say "use a Facade here" instead of explaining a whole design. |
Problem | When should we use it? What situation or symptom tells us it fits? |
Solution | Which classes/objects take part, what are their roles and how do they collaborate? (An abstract description, not finished code.) |
Consequences | What do we gain and what do we pay? Every pattern has trade-offs: more classes, more indirection, extra memory, and so on. |
The full GoF template also lists intent, also-known-as names, motivation, applicability, structure (a class diagram), participants, collaborations, implementation tips, sample code, known uses and related patterns. You will see these headings in many pattern references.
The consequences part is the one beginners skip, and it is the most important. A pattern is a trade-off, not a free upgrade.
The Three Categories of GoF Patterns
The GoF patterns are grouped by purpose, that is, by the kind of problem they solve.
Category | Concerned with | Count | Patterns |
|---|---|---|---|
Creational | How objects are created — hiding which concrete class is instantiated and how | 5 | Abstract Factory, Builder, Factory Method, Prototype, Singleton |
Structural | How classes and objects are composed into larger structures | 7 | Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy |
Behavioral | How objects communicate and share responsibilities | 11 | Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor |
5 + 7 + 11 = 23 patterns. A quick way to remember the split: "Create, Structure, Behave".
The book also classifies patterns by scope:
Class patterns work through inheritance, so the relationships are fixed at compile time. Examples: Factory Method, the class form of Adapter, Template Method, Interpreter.
Object patterns work through object composition, so the relationships can change at run time. Most patterns are object patterns.
One-Line Intent of Each Pattern
You don't need to memorise all 23 in depth, but you should be able to say in one line what each does.
Pattern | Intent in one line |
|---|---|
Singleton | Ensure a class has only one instance and give a global access point to it |
Factory Method | Let subclasses decide which class to instantiate |
Abstract Factory | Create families of related objects without naming their concrete classes |
Builder | Construct a complex object step by step |
Prototype | Create new objects by copying an existing object |
Adapter | Convert one interface into another that clients expect |
Bridge | Separate an abstraction from its implementation so both can vary independently |
Composite | Treat individual objects and groups of objects (trees) uniformly |
Decorator | Add responsibilities to an object dynamically by wrapping it |
Facade | Provide one simple interface to a complex subsystem |
Flyweight | Share many fine-grained objects efficiently to save memory |
Proxy | Provide a stand-in that controls access to another object |
Chain of Responsibility | Pass a request along a chain of handlers until one handles it |
Command | Wrap a request as an object (so it can be queued, logged or undone) |
Interpreter | Represent a simple language's grammar as classes and evaluate sentences |
Iterator | Access elements of a collection one by one without exposing its internals |
Mediator | Make objects talk through a central mediator instead of directly |
Memento | Capture and restore an object's state without breaking encapsulation |
Observer | When one object changes, notify all its dependents automatically |
State | Let an object change its behaviour when its internal state changes |
Strategy | Make a family of algorithms interchangeable at run time |
Template Method | Fix the skeleton of an algorithm in a base class; let subclasses fill in steps |
Visitor | Add new operations to a class hierarchy without changing those classes |
The Principles Behind the Patterns
Patterns are not random tricks. Almost all of them apply a few design principles that you have already met in this tutorial.
1. Program to an Interface, Not an Implementation
This is the first principle stated in the GoF book. Declare variables and parameters using an interface or abstract type, so the code works with any implementation.
List<String> names = new ArrayList<>(); // good: code depends on List
ArrayList<String> names2 = new ArrayList<>(); // works, but ties code to one classIf you later switch to LinkedList, only the line with new changes. This is the same idea as the Dependency Inversion Principle from SOLID: Interface Segregation & Dependency Inversion.
2. Favour Object Composition over Class Inheritance
The second GoF principle. Inheritance is decided at compile time and exposes the parent's internals to the child ("white-box reuse"). Composition — an object holding another object and delegating to it — can be changed at run time and only uses the other object's public interface ("black-box reuse"). Strategy, Decorator, Adapter, Observer and many more are built on composition. We discussed has-a relationships in Association, Aggregation & Composition.
3. Encapsulate What Varies
Find the part of your code that is likely to change and put it behind its own interface, separate from the stable part. Each pattern isolates a different "thing that varies":
Pattern | What it lets you vary |
|---|---|
Strategy | The algorithm |
Factory Method / Abstract Factory | Which concrete class gets created |
Observer | Which objects react to a change, and how many |
Decorator | Extra responsibilities of an object |
Adapter | The interface of an existing class |
Iterator | How a collection is traversed |
Template Method | Individual steps of an algorithm |
This also connects to the Open/Closed Principle (SOLID: Single Responsibility & Open/Closed): most patterns let you add new behaviour by adding new classes instead of editing tested ones, and to low coupling from Coupling & Cohesion.
A Pattern You Already Use: Iterator
Every time you write a for-each loop over a List or Set in Java, you are using the Iterator pattern.
Problem: A collection may store its data in an array, a linked list, a tree or a hash table. Client code wants to visit every element without knowing (or depending on) that internal structure.
Solution: The collection gives out a separate iterator object with two simple operations: "is there another element?" and "give me the next one". In Java these are hasNext() and next() from java.util.Iterator, and a class becomes usable in a for-each loop by implementing Iterable.
Let's build our own iterable Range class that produces numbers from start up to (but not including) end, without storing them in any array:
import java.util.Iterator;
import java.util.NoSuchElementException;
class Range implements Iterable<Integer> {
private final int start;
private final int end; // exclusive
Range(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int current = start;
@Override
public boolean hasNext() {
return current < end;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return current++;
}
};
}
}
class Main {
public static void main(String[] args) {
Range range = new Range(1, 5);
for (int n : range) { // the for-each loop asks for an Iterator
System.out.print(n + " ");
}
System.out.println();
Iterator<Integer> it = range.iterator(); // what for-each does behind the scenes
while (it.hasNext()) {
System.out.print(it.next() * 10 + " ");
}
System.out.println();
}
}Output:
1 2 3 4
10 20 30 40 The client loop never knows that Range has no array inside. If tomorrow Range stores its numbers differently, the loop still works. That is the pattern's benefit: traversal is separated from storage.
The four elements for Iterator would be:
Element | Iterator |
|---|---|
Name | Iterator (also called Cursor) |
Problem | Traverse a collection without exposing how it is stored |
Solution | The collection creates an iterator object that keeps the current position and offers |
Consequences | Several traversals can run at the same time (each has its own iterator); collection code stays simpler; one extra class per collection type |
Another Small Pattern: Template Method
The next three chapters cover Singleton, Factory, Builder, Adapter, Decorator, Facade, Observer, Strategy and Command. Template Method is not covered there, but it is small, very common and a nice example of a class pattern based on inheritance, so let's see it here.
Problem: Several classes follow the same overall steps, but one or two steps differ. Copying the whole algorithm into every class duplicates code and the copies drift apart.
Solution: Put the fixed sequence of steps in a final method of an abstract base class (the template method). The steps that vary are abstract methods (or overridable "hook" methods) that subclasses implement.
abstract class ExamResultPublisher {
// The template method: fixed order of steps, subclasses cannot change it
public final void publish(String student, int marks) {
String body = format(student, marks);
send(body);
System.out.println(" [log] result published for " + student);
}
protected abstract String format(String student, int marks); // varies
protected void send(String body) { // default step
System.out.println(body);
}
}
class CsvPublisher extends ExamResultPublisher {
@Override
protected String format(String student, int marks) {
return student + "," + marks;
}
}
class JsonPublisher extends ExamResultPublisher {
@Override
protected String format(String student, int marks) {
return "{\"name\": \"" + student + "\", \"marks\": " + marks + "}";
}
}
class TemplateDemo {
public static void main(String[] args) {
ExamResultPublisher p1 = new CsvPublisher();
ExamResultPublisher p2 = new JsonPublisher();
p1.publish("Ananya", 87);
p2.publish("Rahul", 92);
}
}Output:
Ananya,87
[log] result published for Ananya
{"name": "Rahul", "marks": 92}
[log] result published for RahulNotice:
publish()isfinal, so no subclass can skip the logging step or change the order.The base class calls the subclass's
format(), not the other way around. This is often called the Hollywood Principle: "Don't call us, we'll call you."send()has a default body, so subclasses may override it but don't have to. Such optional steps are called hooks.
You have seen this pattern earlier in the tutorial whenever an abstract class contained both concrete and abstract methods (Abstract Classes vs Interfaces). The JDK's AbstractList is a real example: you implement get() and size(), and it provides iterator(), indexOf(), contains() and more on top of them.
Design Patterns in the Java Standard Library
The JDK itself is full of GoF patterns. Recognising them is a common interview question.
Pattern | Where you see it in Java |
|---|---|
Iterator |
|
Singleton |
|
Factory method (static factories) |
|
Builder |
|
Decorator |
|
Adapter |
|
Strategy |
|
Command |
|
Observer | GUI event listeners, |
Template Method |
|
Prototype |
|
Note: static methods like List.of() are usually called static factory methods. They are inspired by the factory idea but are not exactly the GoF Factory Method pattern, which uses subclassing. We will see the difference in the next chapter.
Benefits and Costs of Using Patterns
Benefits | Costs / risks |
|---|---|
Proven solutions: you don't reinvent the wheel | More classes and interfaces; code can feel indirect |
Shared vocabulary: "make it a Strategy" says a lot in three words | Overuse: adding patterns "just in case" makes simple code complex |
Flexible, loosely coupled designs that are easier to extend | A pattern used for the wrong problem makes things worse |
Easier to understand frameworks built from patterns | Some patterns are less needed in modern languages (e.g. a lambda can replace a one-method Strategy or Command class) |
A good rule of thumb: let the problem pull the pattern in. Write simple code first. When you feel a specific pain (a growing if-else chain on types, duplicated algorithms, objects that need to be notified), then look for the pattern that removes that pain.
Anti-Patterns
An anti-pattern is a common "solution" that looks reasonable but usually causes more problems than it solves. Knowing them is as useful as knowing patterns:
God Object — one huge class that knows and does everything (violates Single Responsibility).
Spaghetti Code — tangled control flow with no clear structure.
Golden Hammer — using your favourite pattern or tool for every problem ("everything is a Singleton").
Copy-Paste Programming — duplicating code instead of abstracting it.
Lava Flow — dead or unclear code nobody dares to remove.
Common Mistakes
Thinking a pattern is code you can copy. It is a description of roles and relationships. Your classes, names and details will differ every time.
Using patterns to look smart. A 50-line program does not need a Factory, a Builder and a Singleton. Patterns should reduce complexity, not add it.
Ignoring the consequences. Every pattern has a cost. Singleton, for example, introduces global state and makes testing harder.
Confusing design patterns with architectural patterns. MVC and microservices describe whole applications; GoF patterns describe a few cooperating classes.
Mixing up the counts. GoF = 23 patterns: 5 creational, 7 structural, 11 behavioral.
Interview Questions
What is a design pattern? Why do we use them?
A design pattern is a general, reusable solution to a commonly occurring design problem. We use them because they are proven, they give developers a shared vocabulary, and they usually produce flexible, loosely coupled code that is easy to extend.
Who are the Gang of Four and what are the three categories of GoF patterns?
Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, authors of Design Patterns: Elements of Reusable Object-Oriented Software (1994). Their 23 patterns are grouped into creational (5), structural (7) and behavioral (11).
What is the difference between a design pattern and an algorithm?
An algorithm is a precise sequence of steps that solves a computational problem and can be written once as code. A design pattern describes how classes and objects should be arranged and collaborate to solve a design problem; it must be adapted and implemented anew each time.
Name some design patterns used in the JDK.
Iterator (java.util.Iterator), Decorator (BufferedReader), Adapter (InputStreamReader), Strategy (Comparator), Command (Runnable), Singleton (Runtime.getRuntime()), Template Method (AbstractList), Builder (StringBuilder).
What does "favour composition over inheritance" mean?
Prefer building behaviour by having objects hold and delegate to other objects rather than by extending classes. Composition can be changed at run time, keeps classes loosely coupled, and avoids deep, fragile class hierarchies.
What is an anti-pattern? Give an example.
A commonly used approach that looks like a solution but usually creates bigger problems. Example: a God Object, a single class that holds most of the program's data and logic, making it hard to understand, test and change.
Summary
A design pattern is a named, reusable solution to a recurring design problem — a template, not finished code.
The idea came from architect Christopher Alexander; the 1994 Gang of Four book catalogued 23 patterns.
Each pattern has a name, problem, solution and consequences.
Categories: Creational (5, object creation), Structural (7, composing classes/objects), Behavioral (11, communication and responsibility).
Core principles: program to an interface, favour composition over inheritance, encapsulate what varies.
Iterator separates traversal from storage; Template Method fixes an algorithm's skeleton and lets subclasses fill in steps.
Use patterns when a real problem calls for them; overuse is itself an anti-pattern.
In the next chapter, Creational Patterns: Singleton, Factory & Builder, we will look at three patterns that control how objects are created.