What a pattern is
A pattern is not code you copy. It’s a description of a problem, a shape of solution, and the trade-offs, written down because experienced developers kept arriving at the same answer. The idea came from architecture: Christopher Alexander’s 1977 book A Pattern Language described recurring solutions in building design. In 1994, Gamma, Helm, Johnson and Vlissides, the “Gang of Four”, applied it to object-oriented software.
The three families
| Family | Question it answers | Examples |
|---|---|---|
| Creational | How are objects created? | Factory, Builder, Singleton |
| Structural | How are objects combined? | Adapter, Decorator, Facade |
| Behavioral | How do objects talk and share work? | Observer, Strategy, Iterator, Command |
The ten you’ll meet most
| Pattern | Problem | Everyday example |
|---|---|---|
| Factory | Create an object without naming its exact class. | open() returning a text or binary file object. |
| Builder | Assemble a complex object step by step. | Query builders, StringBuilder. |
| Singleton | Exactly one shared instance. | A logger or config object. Often overused. |
| Adapter | Make one interface fit another. | Wrapping an old API so new code can call it. |
| Decorator | Add behaviour by wrapping, not subclassing. | Python’s @cache, middleware layers. |
| Facade | One simple front for a complicated subsystem. | requests.get() hiding sockets, TLS and retries. |
| Observer | Notify many listeners when something happens. | DOM events, pub/sub, reactive UI state. |
| Strategy | Swap an algorithm at run time. | Passing a key function to sort. |
| Iterator | Walk a collection without knowing its insides. | for x in collection. |
| Command | Turn an action into an object. | Undo stacks, job queues. |
Example: Observer
A publisher keeps a list of listeners and calls each one when an event happens. The publisher doesn’t know what the listeners do, and listeners can be added without editing it. That’s the open/closed principle in action.
class Publisher:
"""Observer pattern: listeners subscribe, and every event reaches all of them."""
def __init__(self):
self._listeners = []
def subscribe(self, listener):
self._listeners.append(listener)
def publish(self, event):
# The publisher doesn't know what the listeners do with the event.
for listener in self._listeners:
listener(event)// Observer pattern: listeners subscribe, and every event reaches all of them.
class Publisher {
#listeners = [];
subscribe(listener) {
this.#listeners.push(listener);
}
publish(event) {
// The publisher doesn't know what the listeners do with the event.
for (const listener of this.#listeners) listener(event);
}
}// Publisher is the Observer pattern: listeners subscribe,
// and every event reaches all of them.
type Publisher struct {
listeners []func(event string)
}
func (p *Publisher) Subscribe(listener func(event string)) {
p.listeners = append(p.listeners, listener)
}
func (p *Publisher) Publish(event string) {
// The publisher doesn't know what the listeners do with the event.
for _, listener := range p.listeners {
listener(event)
}
}// Observer pattern: listeners subscribe, and every event reaches all of them.
struct Publisher {
listeners: Vec<Box<dyn Fn(&str)>>,
}
impl Publisher {
fn new() -> Self {
Publisher { listeners: Vec::new() }
}
fn subscribe(&mut self, listener: impl Fn(&str) + 'static) {
self.listeners.push(Box::new(listener));
}
fn publish(&self, event: &str) {
// The publisher doesn't know what the listeners do with the event.
for listener in &self.listeners {
listener(event);
}
}
}In the test for this code, one listener sends an email and another a text message. Adding a third, say a push notification, means one more subscribe call and no change to Publisher.
Common mistakes
- Pattern-first design. Starting with “this needs a factory” before there’s a problem produces layers nobody needs.
- Singleton as a global. A singleton is a global variable with a nicer name. It hides dependencies and makes tests share state. Prefer passing the object in, as in dependency injection.
- Forgetting to unsubscribe. A listener that’s never removed keeps its object alive, a classic memory leak in UI code. Real publishers return an unsubscribe function or handle.
Check yourself
Check yourself
You wrap an old payment SDK so your code can call it through your own PaymentGateway interface. Which pattern is that?
An adapter converts one interface into another that the caller expects. A facade simplifies a subsystem, and a decorator adds behaviour while keeping the same interface.
Check yourself
button.addEventListener('click', handler) is an example of which pattern?
The button is the publisher and handler is a listener. Any number of listeners can subscribe, and the button notifies all of them on each click.
Sources
- Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (1994).
- Christopher Alexander, Sara Ishikawa and Murray Silverstein, A Pattern Language (1977).
- Eric Freeman and Elisabeth Robson, Head First Design Patterns, 2nd edition (2020).
Finished this page?
Your list