programmingconcepts

§ 7.2 · Design

Design patterns

Named, reusable solutions to problems that keep coming up in software design, like Observer, Strategy and Factory.

Design patterns are named, reusable solutions to recurring design problems. The 1994 book by the "Gang of Four" catalogued 23, in three families: creational patterns for making objects, structural patterns for combining them, and behavioral patterns for how they communicate. Their main value is a shared vocabulary: saying "use an observer" explains a whole design in three words.

Catalogued
1994, by the "Gang of Four"
Families
Creational, structural, behavioral
Original count
23
Example here
Observer
Requires
SOLIDObjects and classes

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)

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

  1. Pattern-first design. Starting with “this needs a factory” before there’s a problem produces layers nobody needs.
  2. 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.
  3. 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?

Check yourself

button.addEventListener('click', handler) is an example of which pattern?

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).

Newsletter

One new concept each week, by email.

Signup opens soon.