Design Patterns Overview

Named, reusable solutions to recurring design problems, and when they help or just add layers.

What is it?

A design pattern is a proven shape for solving a problem that keeps coming up in software design. It isn't a library you import; it's a vocabulary. Saying "wrap it in an Adapter" or "use a Strategy here" communicates a whole design in two words.

The classic catalogue (from the 1994 "Gang of Four" book) groups patterns into three families:

- Creational: how objects get created. Factory (choose which class to create), Builder (assemble a complex object step by step), Singleton (exactly one instance). - Structural: how objects are composed. Adapter (make one interface look like another), Decorator (wrap an object to add behaviour), Facade (a simple front for a complex subsystem). - Behavioral: how objects communicate and divide responsibilities. Strategy (swap an algorithm), Observer (notify subscribers of changes), Command (turn a request into an object you can queue, log or undo).

Patterns are tools, not goals. Many were invented to work around limits of 1990s C++ and Java. In languages with first-class functions, a Strategy is often just a function argument, and a Command is just a closure. A pattern applied where the problem doesn't exist only adds indirection.

Explain like I'm 10

Patterns are like architectural terms such as 'open-plan kitchen' or 'load-bearing wall'. Builders don't reinvent them for every house, and saying the name conveys a lot. But putting a load-bearing wall where nothing needs holding up just makes the house harder to change.

Examples

Strategy: pass the varying behaviour in (TypeScript)

type ShippingStrategy = (weightKg: number) => number;

const standardShipping: ShippingStrategy = (weightKg) => 5 + weightKg * 1.2;
const expressShipping: ShippingStrategy = (weightKg) => 15 + weightKg * 2.5;

function checkoutTotal(subtotal: number, weightKg: number, shipping: ShippingStrategy) {
  return subtotal + shipping(weightKg);
}

checkoutTotal(40, 2, expressShipping); // 60

Adapter and Decorator (Python)

class LegacyMailer:                       # third-party API we can't change
    def send_mail(self, address, subject, body): ...

class EmailAdapter:                       # Adapter: fits our Notifier interface
    def __init__(self, mailer):
        self.mailer = mailer
    def notify(self, user, message):
        self.mailer.send_mail(user.email, "Notification", message)

class LoggingNotifier:                    # Decorator: same interface, extra behaviour
    def __init__(self, inner):
        self.inner = inner
    def notify(self, user, message):
        print("notifying", user.id)
        self.inner.notify(user, message)

notifier = LoggingNotifier(EmailAdapter(LegacyMailer()))

The Adapter changes the interface; the Decorator keeps the interface and adds behaviour. Both rely on composition, so they stack.

Observer (JavaScript)

class Store {
  #listeners = new Set();
  #state = { count: 0 };

  subscribe(listener) {
    this.#listeners.add(listener);
    return () => this.#listeners.delete(listener);   // unsubscribe function
  }

  increment() {
    this.#state = { count: this.#state.count + 1 };
    this.#listeners.forEach((listener) => listener(this.#state));
  }
}

const store = new Store();
const unsubscribe = store.subscribe((state) => console.log("count:", state.count));
store.increment();   // count: 1
unsubscribe();       // forgetting this is a classic memory leak

How it works

Most patterns share two moves: program to an interface (depend on what an object does, not its concrete class) and prefer composition (combine small objects rather than building deep inheritance trees).

Creational - Factory: a function or method decides which concrete type to construct (createParser("csv")), so callers don't depend on concrete classes. - Builder: separates constructing a complex object from its representation; useful when there are many optional parameters (new RequestBuilder().url(u).timeout(5).build()). Languages with named/default arguments need it less. - Singleton: guarantees one instance with global access. It's often an anti-pattern: it's global mutable state in disguise, hides dependencies, makes tests share state, and is awkward with concurrency. Prefer creating one instance at startup and passing it in (dependency injection).

Structural - Adapter: translates one interface to another expected by the client. - Decorator: wraps an object with the same interface to add behaviour (logging, caching, retries); wrappers can stack. - Facade: one simple interface over a complicated subsystem.

Behavioral - Strategy: encapsulates interchangeable algorithms behind one interface. - Observer: subjects keep a list of subscribers and notify them of changes (DOM events, reactive stores, pub/sub). - Command: wraps a request as an object with an execute (and often undo), enabling queues, retries, logging, and undo/redo.

When patterns hurt. Each pattern adds a layer. Applied speculatively ("we might need another implementation someday") they produce AbstractFactoryFactory code that is harder to read and change than the plain version. Introduce a pattern when duplication or rigidity is actually hurting, not before.

Creational          Structural             Behavioral
 ----------          ----------             ----------
 Factory             Adapter                Strategy
 Builder             Decorator              Observer
 Singleton (!)       Facade                 Command

 Decorator stacking:
   client --> LoggingNotifier --> RetryNotifier --> EmailAdapter --> LegacyMailer
              (same interface)     (same interface)  (adapts interface)

 Observer:
   Subject --notify--> [listener 1]
           --notify--> [listener 2]
           --notify--> [listener 3]

Why does it exist?

Developers kept solving the same design problems from scratch and giving the solutions different names. Cataloguing them gave teams a shared vocabulary and a set of known trade-offs. Patterns also capture hard-won principles, like depending on abstractions and favouring composition, in concrete, teachable form.

When to use it

- Strategy when you have growing if/else or switch chains choosing between algorithms. - Adapter when integrating a third-party or legacy API whose interface doesn't match yours. - Decorator for cross-cutting concerns (logging, caching, retries, metrics) that should wrap many implementations. - Facade to give the rest of the codebase one clean entry point into a messy subsystem. - Observer for event systems and UI state updates. - Command for undo/redo, job queues, and audit logs of actions. - Factory/Builder when construction logic is complex or depends on config.

When not to use it

- When there's only one implementation and no real sign of a second; a plain function or class is clearer. - When the language already provides the feature: first-class functions replace most Strategy and Command classes; modules already act as single instances. - Singleton for anything with mutable state or that tests need to replace; pass dependencies explicitly instead. - Observer chains that get long and implicit: debugging "who changed this and why" through several layers of notifications becomes very hard.

Common mistakes

  • Applying patterns because they're known, not because the problem needs them, producing layers of interfaces with one implementation each.

  • Using a Singleton as a convenient global, which hides dependencies and makes tests leak state into each other.

  • Confusing Adapter (changes the interface) with Decorator (keeps the interface, adds behaviour) and Facade (simplifies a whole subsystem).

  • Forgetting to unsubscribe observers, leaking memory and running handlers for components that no longer exist.

  • Writing Strategy or Command class hierarchies in a language where passing a function would do the same job in a few lines.

Practice exercises

  1. Easy:

    Refactor a function with a switch over discount types (none, percentage, fixed, buy-one-get-one) into the Strategy pattern using a map from type name to function.

  2. Medium:

    Write an HTTP client interface with one real implementation, then add a caching decorator and a retry decorator. Show they can be stacked in either order and explain how the order changes behaviour.

  3. Hard:

    Build a small text editor model with insert and delete operations implemented as Commands that support undo and redo. Then replace a Singleton-based logger in it with dependency injection and write a test that uses a fake logger.

Interview questions

What is a design pattern?

A named, reusable solution to a recurring design problem, described in terms of roles and relationships rather than specific code. Patterns give teams a shared vocabulary and known trade-offs; they're templates, not libraries.

What are the three categories of GoF patterns?

Creational (how objects are created: Factory, Builder, Singleton, Prototype), Structural (how objects are composed: Adapter, Decorator, Facade, Proxy, Composite), and Behavioral (how objects interact: Strategy, Observer, Command, Iterator, State).

Why is Singleton often called an anti-pattern?

It's global state with a nicer name. It hides dependencies, couples code to a concrete class, makes tests interfere through shared state, complicates concurrency, and makes later 'we need two of these' changes painful. Create one instance at the composition root and inject it instead.

What is the difference between Adapter, Decorator and Facade?

Adapter converts one interface into another a client expects. Decorator wraps an object with the same interface to add behaviour. Facade provides a new, simpler interface over a whole subsystem of several objects.

How does Strategy relate to first-class functions?

Strategy encapsulates interchangeable algorithms behind one interface. In languages with first-class functions, the interface is just a function type, and each strategy is a function, so the pattern often reduces to passing a function argument.

When would you use the Builder pattern?

When an object has many optional parameters or must be assembled in steps with validation at the end, such as HTTP requests, SQL queries, or complex config. It avoids telescoping constructors. Languages with named and default parameters need it less.

What problem does the Observer pattern solve, and what are its pitfalls?

It lets a subject notify many dependents of changes without knowing their concrete types, decoupling producers from consumers. Pitfalls: memory leaks from forgotten subscriptions, unpredictable notification order, cascading updates, and hard-to-trace control flow.

What is the Command pattern good for?

Representing an action as an object with everything needed to execute it later. That enables queuing, scheduling, retrying, logging, and undo/redo (by pairing execute with undo). Job queues and editor history are classic uses.

How do you decide whether to introduce a pattern?

Wait for the pain: duplicated branching, code that is hard to extend or test, or a real second implementation. Then pick the simplest pattern that removes it. If the pattern adds more indirection than it removes complexity, keep the plain code.

Factory Method vs Abstract Factory?

Factory Method defines a method that subclasses (or a function) use to decide which single product to create. Abstract Factory is an object providing methods to create a family of related products that must be used together, such as all widgets for one UI theme.