If you have written a few hundred lines of object-oriented code, you have probably solved the same problem twice: one object has to tell several others that something changed, or a long if-else chain picks between algorithms. Design patterns give those recurring problems a name and a proven shape, so you can recognise the problem quickly and talk about the fix in one word.
We will start with where the idea came from and the 23 classic patterns in their three groups. Then you will refactor a small temperature sensor in Python with the Observer pattern, count exactly what changes, and finish with the mistakes to avoid and the questions examiners like to ask.

Design patterns are named, reusable solutions to problems that keep coming up in software design, described so you can adapt them to your own code.
- Name
- Problem it solves
- Solution (classes and how they collaborate)
- Consequences and trade-offs
- 23 classic patterns in 3 groups
Where design patterns come from
The word comes from architecture. In A Pattern Language (1977), Christopher Alexander and his co-authors described patterns as a problem that occurs over and over again, plus the core of a solution you can reuse a million times without doing it the same way twice.
In 1994, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides applied that idea to object-oriented software. Their book, Design Patterns: Elements of Reusable Object-Oriented Software, is why the four authors are known as the Gang of Four (GoF). It catalogues 23 patterns and is still the reference most courses use.
The four elements of a pattern
The GoF book says every pattern has four essential elements. Knowing them helps you read any pattern description, not only the classic 23.
The book also states two principles that run through almost every pattern: program to an interface, not an implementation, and favour object composition over class inheritance. These are the same ideas behind the SOLID principles, especially dependency inversion and open closed.
The three groups of design patterns
The GoF book sorts its patterns by purpose. Creational patterns deal with how objects are created, structural patterns with how classes and objects are combined, and behavioral patterns with how objects interact and share responsibility.
| Pattern | What it does |
|---|---|
| Abstract Factory | Creates families of related objects without naming their concrete classes |
| Builder | Separates the construction of a complex object from its representation |
| Factory Method | Lets subclasses decide which class to instantiate |
| Prototype | Creates new objects by copying an existing instance |
| Singleton | Ensures a class has only one instance, with a global point of access |
| Pattern | What it does |
|---|---|
| Adapter | Converts one interface into another that clients expect |
| Bridge | Decouples an abstraction from its implementation so both can vary |
| Composite | Builds tree structures and treats single objects and groups the same way |
| Decorator | Attaches extra responsibilities to an object at runtime |
| Facade | Gives one simple interface to a complex subsystem |
| Flyweight | Shares objects to support large numbers of small ones efficiently |
| Proxy | Provides a placeholder that controls access to another object |
| Pattern | What it does |
|---|---|
| Chain of Responsibility | Passes a request along a chain until one handler deals with it |
| Command | Wraps a request in an object, so it can be queued, logged or undone |
| Interpreter | Represents a simple grammar and evaluates sentences in it |
| Iterator | Walks through a collection without exposing how it is stored |
| Mediator | Puts the interaction between many objects into one object |
| Memento | Saves and restores an object’s state without breaking encapsulation |
| Observer | Notifies all dependents automatically when one object changes |
| State | Changes an object’s behaviour when its internal state changes |
| Strategy | Makes a family of algorithms interchangeable |
| Template Method | Fixes the steps of an algorithm and lets subclasses fill some in |
| Visitor | Adds a new operation over a structure without changing its classes |
How the Observer pattern works
Observer is a good first pattern because you meet it everywhere: GUI events, spreadsheet cells and the model and view in Smalltalk MVC, which the GoF book uses as its opening example. Its intent is to define a one-to-many dependency, so that when one object changes state, all its dependents are notified and updated automatically.
The object being watched is the subject. Each observer registers with it through attach() and implements a single update() method. The subject keeps a list and calls update() on every entry when its state changes, without knowing what each observer does.
Push or pull: what the subject sends
The GoF book describes two ways to pass data. In the push model the subject sends detailed information about the change with every call. In the pull model it sends very little, often just itself, and each observer asks for what it needs. The example below uses the pull model: update(self) hands over the sensor and each observer reads sensor.celsius.
Worked example: refactoring with the Observer pattern
Here is a temperature sensor that talks to three other objects directly. Every new listener means editing the sensor class.
class TemperatureSensor:
def __init__(self, display, logger, alarm):
self.display, self.logger, self.alarm = display, logger, alarm
def set_reading(self, celsius):
self.celsius = celsius
self.display.show(celsius)
self.logger.write(celsius)
if celsius > 80:
self.alarm.ring(celsius)
After the refactoring, the sensor only knows that its observers have an update() method.
class TemperatureSensor: # the subject
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def set_reading(self, celsius):
self.celsius = celsius
for observer in self._observers:
observer.update(self) # pull model: pass the subject
class HighTempAlarm: # one concrete observer
def __init__(self, limit):
self.limit = limit
def update(self, sensor):
if sensor.celsius > self.limit:
print(f"ALARM: {sensor.celsius} C is over {self.limit} C")
- Given
- Refactored TemperatureSensor with three observers attached (Display, Logger, HighTempAlarm with limit 80 °C); readings 72, 85 and 78 °C
- Find
- Number of update() calls, number of alarms, and the change needed to add an SMS alert
- Assumptions
- Single thread; observers are notified in the order they were attached; each set_reading() call notifies every observer once
- Step 1Calls per reading = number of observers = 3, so 3 readings × 3 observers = 9 update() calls
- Step 2Alarm check against the 80 °C limit: 72 no, 85 yes, 78 no, so 1 alarm
- Step 3Add SmsAlert as a new class with update(), then sensor.attach(SmsAlert()): 3 readings × 4 observers = 12 calls
- Step 4Lines changed inside TemperatureSensor: 0
Limitations: Updates run one after another in the sensor's thread, so a slow observer delays the rest. Observers must detach when no longer needed, or the list keeps them alive.
Running the code in Python confirms it: the display prints all three readings, the alarm fires once at 85 °C, and the counter reaches 9, then 12 with the fourth observer.
How to apply a design pattern
Once you have chosen a pattern, the GoF book gives a short procedure for using it.
- Read the pattern once for an overview, paying attention to when it applies and its consequences.
- Study the structure and participants, so you know which classes exist and how they collaborate.
- Look at the sample code to see one concrete implementation.
- Choose names that make sense in your code, such as TemperatureSensor instead of Subject.
- Define the classes and interfaces, then change the existing code that the pattern affects.
- Implement the operations, using the pattern’s collaborations as a guide.
Martin Fowler’s book Refactoring describes the same moves at a smaller scale. For example, Replace Conditional with Polymorphism turns a long if-else chain on a type field into separate classes, which is often how a Strategy or State pattern appears in real code.
Design patterns in modern languages
Some patterns are now part of the language. Python’s iterator protocol (__iter__ and __next__) and Java’s java.util.Iterator interface are the Iterator pattern built in. In Python, functions are objects, so a Strategy can often be a plain function passed as an argument.
Watch the names, though. Python’s @decorator syntax wraps a function, while the GoF Decorator wraps an object behind the same interface to add responsibilities. Java’s own java.util.Observer interface has been deprecated since Java 9.
- Start from the problem: pick a pattern because the code has the problem it solves, not to use the pattern.
- Separate what varies: Head First Design Patterns gives this as its first design principle, and it is the core of Strategy and Observer.
- Use the pattern name in code and reviews, so other developers recognise the structure.
- Pattern for its own sake: adding factories and interfaces for variations that never arrive.
- Naive Singleton in threaded code: Head First Design Patterns shows that two threads can each create an instance unless creation is synchronised.
- Forgotten observers: never detaching observers, which wastes memory and causes unexpected updates.
Design patterns interview and viva questions
Q1What is a design pattern?
A named, reusable solution to a recurring design problem, described by its name, the problem, the solution and its consequences. It is a template you adapt, not finished code.
Q2What are the three groups of GoF design patterns?
Creational (5 patterns, how objects are created), structural (7, how classes and objects are composed) and behavioral (11, how objects interact and share responsibility).
Q3What is the intent of the Observer pattern?
To define a one-to-many dependency so that when one object changes state, all its dependents are notified and updated automatically.
Q4What is the difference between Strategy and State?
Strategy lets the client choose between interchangeable algorithms. State changes the object's behaviour by itself when its internal state changes.
Q5Which two principles does the GoF book stress?
Program to an interface, not an implementation, and favour object composition over class inheritance.
Related reading
Frequently asked questions
How many design patterns are there?
The Gang of Four book from 1994 catalogues 23 patterns: 5 creational, 7 structural and 11 behavioral. Later books add many more, such as the enterprise application patterns described by Martin Fowler, so there is no fixed total.
Are design patterns still relevant in modern languages?
Yes, but some are now built into the language. Python and Java both have an iterator protocol in the standard library, and in Python a function can often play the role of a Strategy object. The ideas stay useful even when the code gets shorter.
Should a beginner learn design patterns before SOLID?
Learn them together. The SOLID principles explain why code should depend on abstractions and stay open for extension, and many patterns, such as Strategy, Observer and Adapter, are concrete ways to do exactly that.
References
- E. Gamma, R. Helm, R. Johnson and J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994
- E. Freeman and E. Robson, Head First Design Patterns, 2nd ed., O'Reilly Media, 2020
- M. Fowler, Refactoring: Improving the Design of Existing Code, 2nd ed., Addison-Wesley, 2018
- M. Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002
- C. Alexander, S. Ishikawa and M. Silverstein, A Pattern Language, Oxford University Press, 1977
- Python Software Foundation, Python 3 Documentation: Glossary (iterator, decorator) and Built-in Types (iterator types), docs.python.org
- Oracle, Java SE 17 API Specification: java.util.Iterator and java.util.Observer
Get one engineering email a week
New articles, worked examples and study notes every week. Free, no spam, unsubscribe any time.