On this page

Pattern Selection Guide

Knowing 25 patterns is not the hard part. The hard part is the moment in an interview, or in a code review, when you are looking at a specific mess and need to decide which pattern (if any) makes it better. Pattern catalogues are organised by solution: here is Strategy, here is its structure, here are its consequences. Real problems arrive the other way round. You see a switch that keeps growing, or three classes that copy the same method with two lines changed, and you have to work backwards to a name.

This page is organised by problem. It has four parts:

  1. A smell-to-pattern table that starts from what you see in the code and points to the pattern pages in this module.
  2. Look-alike comparisons for the pairs and triples that share a class diagram but solve different problems, each with short runnable code.
  3. How to justify a pattern in an interview, with a script you can follow and phrases that land badly.
  4. When not to use any pattern, because the most common pattern mistake in an LLD round is using one where none was needed.

If you want the patterns themselves first, the grouped overviews (creational, structural, behavioral) are a quick tour, and each pattern below links to its own page.

The one question behind every pattern

Almost every classic pattern answers the same question: what is going to change, and how do I keep that change from spreading? A pattern draws a boundary around the thing that varies so that the rest of the code doesn't have to know about it. Strategy puts a boundary around an algorithm. Factory Method puts one around the choice of class to instantiate. Observer puts one around the list of things that react to an event. Adapter puts one around a foreign interface.

So the first step in choosing a pattern is never "which pattern fits?" It is "what varies here, and does it vary independently of the code around it?" If you can't name the thing that varies, you don't need a pattern yet. If you can, the table below usually narrows it to one or two candidates.

What variesPattern familyExamples
Which class gets createdCreationalFactory Method, Abstract Factory, Prototype
How a complex object is assembledCreationalBuilder
How many instances exist, and their lifetimeCreationalSingleton, Object Pool, Flyweight
The interface a client seesStructuralAdapter, Facade
Extra behaviour around a callStructuralDecorator, Proxy
Two dimensions of a hierarchyStructuralBridge
Part-whole nestingStructuralComposite
An algorithm or policyBehavioralStrategy, Template Method
Behaviour as the object's lifecycle moves onBehavioralState
Who reacts to an eventBehavioralObserver, Mediator
A request as data to run later, undo or queueBehavioralCommand, Memento
Who handles a requestBehavioralChain of Responsibility
Operations over a fixed set of typesBehavioralVisitor, Iterator
Rules that business people writeBehavioral / beyond GoFInterpreter, Specification
What happens when something is absentBeyond GoFNull Object
Where data livesBeyond GoFRepository
Who supplies a dependencyBeyond GoFDependency Injection

From smell to pattern

Each row starts with something you can see in code or hear in requirements. The "Watch out" column names the most common wrong turn. "Consider" means consider: in every row, the right answer is sometimes "a plain function" or "leave it alone".

Creating objects

Smell you seeWhat is really varyingConsiderWatch out
The same switch (type) that picks a class to new appears in several placesThe concrete class for a given inputFactory Method, or a simple factory function or registry mapA one-off switch in one place is fine as it is
A framework or base class needs subclasses to supply "their" productThe product, chosen by the subclassFactory MethodDon't add a creator hierarchy just to wrap one new
Products that must match get mixed up: a dark button with a light dialog, an AWS client with a GCP queueA whole family of related productsAbstract FactoryOverkill if there is only one family or one product per family
A constructor with six or more parameters, several optional, often null or false in a rowThe combination of optional partsBuilder (or named and default arguments in Python, TypeScript object literals)A builder for a three-field value object is noise
Objects created half-valid with setters, then "finished" laterWhen the object is completeBuilder, with validation in build()Exposing setters on the built object defeats it
Creating an object is expensive or needs its concrete class, but you have a configured exampleStarting point of the new objectPrototypeDeep vs shallow copy bugs. Records and structuredClone often suffice
"There must be exactly one" plus global access to itInstance countSingleton, but usually Dependency Injection of one instanceHidden global state and untestable code
An expensive resource (connection, thread, buffer) is created per requestResource lifetimeObject PoolPools of cheap objects slow things down; leaked objects exhaust the pool
Classes call new on their collaborators, so tests can't substitute fakesWho supplies collaboratorsDependency InjectionA DI container is not required. Constructor arguments are enough

Structuring objects

Smell you seeWhat is really varyingConsiderWatch out
A third-party or legacy API's types and quirks leak into domain codeThe foreign interfaceAdapterAdapting your own code you could just change
Classes multiply in two directions: EmailAlert, SmsAlert, UrgentEmailAlert, UrgentSmsAlert...Two independent dimensionsBridgeIf one dimension never changes, plain composition is enough
Client code checks if (node.isFolder()) before recursing; wholes and parts are handled differentlyNesting depthCompositeForcing leaf-only methods onto containers (or vice versa)
Subclasses for every combination of optional extras: CachingLoggingRetryingClientOptional add-on behaviourDecoratorOrder-dependent decorators with no documented order
Callers make five calls to four subsystem classes in a fixed order, and get it wrongThe workflow across a subsystemFacadeA facade that grows into a god class
Memory is dominated by millions of near-identical objects with the same repeated dataShared, immutable intrinsic dataFlyweightOnly worth it with measured memory pressure
You need lazy loading, access checks, caching or a remote stand-in without changing callersAccess to the real objectProxyProxies that hide slow remote calls behind a fast-looking interface

Behaviour and communication

Smell you seeWhat is really varyingConsiderWatch out
An if/else or switch on a mode (pricing plan, payment method, routing rule) that grows with each featureThe algorithmStrategy, often just a functionTwo fixed branches don't need it
The same status field is checked in most methods, and illegal transitions keep sneaking inBehaviour by lifecycle stageState, or a transition tableA three-state enum with one switch is clearer as an enum
A method ends with hard-coded calls to everyone who cares: emailer.send(); search.reindex(); stats.bump();Who reacts to an eventObserverLeaked listeners; hidden ordering assumptions
Requirements mention undo, redo, replay, queueing, scheduling or audit of user actionsThe request itself, as dataCommandCommands that capture mutable references break undo
Several classes copy the same multi-step algorithm with one or two steps differentIndividual steps of a fixed skeletonTemplate Method, or Strategy for the stepsDeep inheritance; subclasses overriding steps they shouldn't
Callers index into your internal list or map, or load everything to loop over part of itTraversalIterator, usually a generatorModifying a collection while iterating it
A request goes through ordered checks (auth, validation, rate limit) or "can you handle this?" handlersWho handles, and in what orderChain of ResponsibilityRequests that fall off the end unhandled, silently
Peer objects all hold references to each other: every widget knows every other widgetCoordination among peersMediatorThe mediator becomes the new god class
You need snapshots and rollback without exposing an object's private fieldsSaved stateMementoSnapshot memory cost; snapshots that alias mutable data
You keep adding operations (print, type-check, optimise) over a stable set of node typesThe operationVisitor, or sealed types plus pattern matchingAdding a new node type now means editing every visitor
Business users want to write rules or formulas in a small languageRules as dataInterpreterGrowing it into a general-purpose language by accident
The same business conditions, combined with and/or/not, are duplicated in validation, filters and queriesThe ruleSpecificationSpecs that can't be translated to the database load whole tables
The same if (x != null) on an optional collaborator, in many methodsBehaviour when absentNull ObjectNull objects for required collaborators hide outages
SQL or ORM calls scattered through domain logicWhere data livesRepositoryA repository per table that just mirrors the ORM
Events must cross a process or service boundaryDelivery and decoupling in timePub-Sub, an event busTreating an in-process observer as if it were durable

A useful habit: when a row matches, open the pattern page and read its "When NOT to use it" section before the implementation. If any of those conditions describe your situation, keep looking.

A decision flowchart

The tables are for lookup. This flowchart is for the moment when you only know roughly what kind of problem you have.

flowchart TD
    Q["What hurts?"] --> C["Creating objects"]
    Q --> S["Fitting objects together"]
    Q --> B["Behaviour that varies"]
    C --> C1{"Many optional parts?"}
    C1 -->|"yes"| Builder["Builder"]
    C1 -->|"no"| C2{"Families that must match?"}
    C2 -->|"yes"| AF["Abstract Factory"]
    C2 -->|"no"| FM["Factory Method or DI"]
    S --> S1{"Interface is wrong?"}
    S1 -->|"one class"| Adapter["Adapter"]
    S1 -->|"whole subsystem"| Facade["Facade"]
    S1 -->|"no, same interface"| S2{"Adding behaviour or controlling access?"}
    S2 -->|"adding"| Decorator["Decorator"]
    S2 -->|"controlling"| Proxy["Proxy"]
    B --> B1{"Who picks the variant?"}
    B1 -->|"caller or config"| Strategy["Strategy"]
    B1 -->|"the object, as it changes"| State["State"]
    B1 -->|"nobody, it's a reaction"| B2{"Do senders know receivers?"}
    B2 -->|"subject keeps a list"| Observer["Observer"]
    B2 -->|"a hub coordinates"| Mediator["Mediator"]
    B2 -->|"only a topic name"| PubSub["Pub-Sub"]

Patterns that look alike

Many patterns share a class diagram. Strategy and State are both "an object delegates to an interface with swappable implementations". Decorator and Proxy are both "a wrapper with the same interface as the thing it wraps". The diagrams can't tell them apart. Intent does: what the pattern is for, who decides which implementation is in play, and when that decision changes. Interviewers like these pairs because they test whether you know the why or only the shape.

Each comparison below has short code that compiles and runs, and ends with a one-line test you can apply.

Strategy vs State

Both delegate behaviour to an object behind an interface. The difference is who chooses the implementation, and whether it changes by itself.

  • In Strategy, the client (or configuration) picks the algorithm and the context keeps it. The strategies don't know about each other, and the context doesn't switch on its own.
  • In State, the object moves itself from one state to the next in response to events. State objects know about the transitions, and the client usually doesn't know which state is active.
// Strategy: the caller chooses how shipping is priced. It never changes on its own.
type ShippingCost = (kg: number) => number;
const standard: ShippingCost = (kg) => 500 + 100 * kg;
const express: ShippingCost = (kg) => 1500 + 200 * kg;

class Shipment {
  constructor(private readonly kg: number, private readonly cost: ShippingCost) {}
  price(): number {
    return this.cost(this.kg);
  }
}

// State: the turnstile changes its own behaviour as events arrive.
interface TurnstileState {
  coin(t: Turnstile): void;
  push(t: Turnstile): "pass" | "blocked";
}
const Locked: TurnstileState = {
  coin: (t) => t.moveTo(Unlocked),
  push: () => "blocked",
};
const Unlocked: TurnstileState = {
  coin: () => {}, // extra coins are kept, the gate stays open
  push: (t) => {
    t.moveTo(Locked);
    return "pass";
  },
};

class Turnstile {
  private state: TurnstileState = Locked;
  moveTo(next: TurnstileState): void {
    this.state = next;
  }
  coin(): void {
    this.state.coin(this);
  }
  push(): "pass" | "blocked" {
    return this.state.push(this);
  }
}

if (new Shipment(2, standard).price() !== 700) throw new Error("standard");
if (new Shipment(2, express).price() !== 1900) throw new Error("express");

const gate = new Turnstile();
if (gate.push() !== "blocked") throw new Error("locked first");
gate.coin();
if (gate.push() !== "pass") throw new Error("unlocked after coin");
if (gate.push() !== "blocked") throw new Error("relocks after pass");
console.log("strategy vs state ok");
StrategyState
Who picks the implementationClient or configurationThe object itself, on each event
Do implementations know each otherNoYes, they name the next state
Changes during the object's lifeRarely, and only when toldConstantly, that's the point
Typical examplePricing, sorting, routing, compressionVending machine, order lifecycle, TCP connection, turnstile

The test: if you can draw a state diagram with arrows between the implementations, it's State. If the implementations are interchangeable alternatives with no arrows between them, it's Strategy. The State page covers the trade-off with a plain enum and switch, which is often the better choice for small machines.

Decorator vs Proxy vs Adapter vs Facade

All four are wrappers. They differ in what interface they expose and why they exist.

Interface it exposesWrapsWhy it exists
DecoratorThe same as the wrapped objectOne object, and decorators stackTo add behaviour (logging, caching, retries)
ProxyThe same as the wrapped objectOne object, often created or located by the proxyTo control access (lazy creation, permissions, remoting)
AdapterA different one, the one the client expectsOne object with the wrong interfaceTo make an incompatible interface fit
FacadeA new, simpler oneA whole subsystem of several objectsTo give clients one easy entry point
interface Store {
  get(key: string): string | undefined;
  put(key: string, value: string): void;
}

class MemoryStore implements Store {
  private readonly data = new Map<string, string>();
  get(key: string) {
    return this.data.get(key);
  }
  put(key: string, value: string) {
    this.data.set(key, value);
  }
}

// Decorator: same interface, adds behaviour, can be stacked.
class CountingStore implements Store {
  reads = 0;
  constructor(private readonly inner: Store) {}
  get(key: string) {
    this.reads++;
    return this.inner.get(key);
  }
  put(key: string, value: string) {
    this.inner.put(key, value);
  }
}

// Proxy: same interface, controls access. Here it delays creating the real store
// and refuses writes for read-only callers.
class GuardedLazyStore implements Store {
  private real: Store | undefined;
  constructor(private readonly create: () => Store, private readonly canWrite: boolean) {}
  private target(): Store {
    return (this.real ??= this.create());
  }
  get(key: string) {
    return this.target().get(key);
  }
  put(key: string, value: string) {
    if (!this.canWrite) throw new Error("read-only access");
    this.target().put(key, value);
  }
}

// Adapter: a legacy client with the wrong shape, made to look like a Store.
class LegacyKvClient {
  private readonly rows: Record<string, string> = {};
  fetchValue(key: string): string | null {
    return this.rows[key] ?? null;
  }
  storeValue(key: string, value: string): boolean {
    this.rows[key] = value;
    return true;
  }
}
class LegacyStoreAdapter implements Store {
  constructor(private readonly client: LegacyKvClient) {}
  get(key: string) {
    return this.client.fetchValue(key) ?? undefined;
  }
  put(key: string, value: string) {
    if (!this.client.storeValue(key, value)) throw new Error("legacy write failed");
  }
}

// Facade: a new, simpler interface over several collaborators.
class ProfileFacade {
  constructor(private readonly store: Store, private readonly audit: string[]) {}
  rename(userId: string, name: string): void {
    const profile = JSON.parse(this.store.get(userId) ?? "{}") as { name?: string };
    profile.name = name.trim();
    this.store.put(userId, JSON.stringify(profile));
    this.audit.push(`renamed ${userId}`);
  }
}

const counted = new CountingStore(new MemoryStore());
counted.put("a", "1");
counted.get("a");
counted.get("b");
if (counted.reads !== 2) throw new Error("decorator");

let created = 0;
const createdSoFar = (): number => created;
const readOnly = new GuardedLazyStore(() => (created++, new MemoryStore()), false);
if (createdSoFar() !== 0) throw new Error("proxy must be lazy");
readOnly.get("x");
if (createdSoFar() !== 1) throw new Error("proxy creates on first use");
let refused = false;
try {
  readOnly.put("x", "1");
} catch {
  refused = true;
}
if (!refused) throw new Error("proxy must guard writes");

const adapted = new LegacyStoreAdapter(new LegacyKvClient());
adapted.put("k", "v");
if (adapted.get("k") !== "v" || adapted.get("missing") !== undefined) throw new Error("adapter");

const audit: string[] = [];
new ProfileFacade(adapted, audit).rename("u1", "  Ada ");
if (JSON.parse(adapted.get("u1")!).name !== "Ada" || audit.length !== 1) throw new Error("facade");
console.log("wrappers ok");

Notice that ProfileFacade happily takes the adapted legacy store. Wrappers combine: a facade over adapted subsystems, a decorator around a proxy. What you call each class depends on the job that class does.

The test: same interface and adds behaviour, Decorator. Same interface and decides whether or when the real call happens, Proxy. Different interface for one class, Adapter. Simpler interface for many classes, Facade. Note that Decorator and Proxy can share identical code (a caching wrapper is called both); the honest answer in an interview is to name the intent you have in mind.

Factory Method vs Abstract Factory vs Builder

All three hide new. They differ in what they produce and how.

  • Factory Method: one product; a method (often overridden by subclasses, or a static creation function) decides which concrete class.
  • Abstract Factory: a family of related products that must be used together; one factory object per family.
  • Builder: one complex product assembled step by step, with validation at the end.
import java.time.Duration;
import java.util.*;

public class CreationalComparison {
    // ---- Factory Method: subclasses decide which single product to make
    interface Notifier { String send(String msg); }
    static final class EmailNotifier implements Notifier { public String send(String m) { return "email:" + m; } }
    static final class SmsNotifier implements Notifier { public String send(String m) { return "sms:" + m; } }

    abstract static class AlertService {
        protected abstract Notifier createNotifier();          // the factory method
        String alert(String msg) { return createNotifier().send(msg.toUpperCase()); }
    }
    static final class EmailAlerts extends AlertService { protected Notifier createNotifier() { return new EmailNotifier(); } }
    static final class SmsAlerts extends AlertService { protected Notifier createNotifier() { return new SmsNotifier(); } }

    // ---- Abstract Factory: a family of products that must match
    interface Button { String render(); }
    interface Dialog { String render(); }
    interface UiKit { Button button(); Dialog dialog(); }
    static final class DarkKit implements UiKit {
        public Button button() { return () -> "dark-button"; }
        public Dialog dialog() { return () -> "dark-dialog"; }
    }
    static final class LightKit implements UiKit {
        public Button button() { return () -> "light-button"; }
        public Dialog dialog() { return () -> "light-dialog"; }
    }
    static String screen(UiKit kit) { return kit.dialog().render() + "+" + kit.button().render(); }

    // ---- Builder: one complex product, assembled step by step, validated once
    record HttpRequest(String method, String url, Map<String, String> headers, Duration timeout) {}
    static final class RequestBuilder {
        private final String url;
        private String method = "GET";
        private final Map<String, String> headers = new LinkedHashMap<>();
        private Duration timeout = Duration.ofSeconds(10);
        RequestBuilder(String url) { this.url = url; }
        RequestBuilder method(String m) { this.method = m; return this; }
        RequestBuilder header(String k, String v) { headers.put(k, v); return this; }
        RequestBuilder timeout(Duration t) { this.timeout = t; return this; }
        HttpRequest build() {
            if (!url.startsWith("https://")) throw new IllegalStateException("https only");
            if (method.equals("POST") && !headers.containsKey("Content-Type"))
                throw new IllegalStateException("POST needs Content-Type");
            return new HttpRequest(method, url, Map.copyOf(headers), timeout);
        }
    }

    public static void main(String[] args) {
        assert new EmailAlerts().alert("disk full").equals("email:DISK FULL");
        assert new SmsAlerts().alert("disk full").equals("sms:DISK FULL");

        assert screen(new DarkKit()).equals("dark-dialog+dark-button");
        assert screen(new LightKit()).equals("light-dialog+light-button");

        HttpRequest req = new RequestBuilder("https://api.example.com/orders")
                .method("POST").header("Content-Type", "application/json")
                .timeout(Duration.ofSeconds(3)).build();
        assert req.headers().size() == 1 && req.timeout().getSeconds() == 3;
        try {
            new RequestBuilder("https://api.example.com").method("POST").build();
            throw new AssertionError("should have failed validation");
        } catch (IllegalStateException expected) { }
        System.out.println("creational ok");
    }
}
Factory MethodAbstract FactoryBuilder
ProducesOne productA family of productsOne complex product
VariesWhich classWhich familyWhich parts and values
Client callsOne methodSeveral methods on one factoryMany setter-like steps, then build()
Typical smellswitch on type to pick a classMismatched products from different familiesLong constructor with optional arguments

The test: "which class?" Factory Method. "Which matching set of classes?" Abstract Factory. "How do I fill in twelve fields safely?" Builder. In practice an Abstract Factory is usually a set of factory methods on one object, and a builder's build() sometimes calls a factory, so they combine freely.

Observer vs Mediator vs Pub-Sub

All three decouple the code that causes something from the code that reacts to it. They differ in who knows whom.

  • Observer: the subject keeps a list of observers and calls them. Observers know the subject (they subscribed to it); the subject knows only the observer interface. Communication is one-to-many, one direction.
  • Mediator: peers talk through a hub that contains the coordination logic. Peers know the mediator but not each other. Communication is many-to-many, and the mediator decides who hears what.
  • Pub-Sub: publishers and subscribers know only a topic name and a broker. Neither knows the other exists. Often asynchronous and, across processes, durable.
// Observer: the subject holds its observers and calls them directly.
type PriceListener = (symbol: string, price: number) => void;
class Ticker {
  private readonly listeners = new Set<PriceListener>();
  constructor(readonly symbol: string) {}
  subscribe(l: PriceListener): () => void {
    this.listeners.add(l);
    return () => this.listeners.delete(l); // always hand back a way to unsubscribe
  }
  update(price: number): void {
    for (const l of this.listeners) l(this.symbol, price);
  }
}

// Mediator: participants only know the room, and the room holds the rules.
class ChatRoom {
  private readonly members = new Map<string, Member>();
  private readonly muted = new Set<string>();
  join(m: Member): void {
    this.members.set(m.name, m);
  }
  mute(name: string): void {
    this.muted.add(name);
  }
  send(from: string, text: string): void {
    if (this.muted.has(from)) return; // coordination logic lives here
    for (const [name, m] of this.members) if (name !== from) m.inbox.push(`${from}: ${text}`);
  }
}
class Member {
  readonly inbox: string[] = [];
  constructor(readonly name: string, private readonly room: ChatRoom) {
    room.join(this);
  }
  say(text: string): void {
    this.room.send(this.name, text);
  }
}

// Pub-Sub: publisher and subscriber share only a topic string.
class Broker {
  private readonly topics = new Map<string, Array<(msg: unknown) => void>>();
  subscribe(topic: string, handler: (msg: unknown) => void): void {
    this.topics.set(topic, [...(this.topics.get(topic) ?? []), handler]);
  }
  publish(topic: string, msg: unknown): number {
    const handlers = this.topics.get(topic) ?? [];
    handlers.forEach((h) => h(msg));
    return handlers.length;
  }
}

const seen: number[] = [];
const acme = new Ticker("ACME");
const stop = acme.subscribe((_s, p) => seen.push(p));
acme.update(10);
stop();
acme.update(11);
if (seen.join() !== "10") throw new Error("observer");

const room = new ChatRoom();
const ana = new Member("ana", room);
const bo = new Member("bo", room);
const cy = new Member("cy", room);
ana.say("hi");
room.mute("bo");
bo.say("spam");
if (bo.inbox.length !== 1 || cy.inbox.length !== 1 || ana.inbox.length !== 0) throw new Error("mediator");

const broker = new Broker();
const shipped: unknown[] = [];
broker.subscribe("order.shipped", (m) => shipped.push(m));
if (broker.publish("order.shipped", { id: 7 }) !== 1) throw new Error("pubsub delivered");
if (broker.publish("order.cancelled", { id: 8 }) !== 0) throw new Error("no subscribers");
console.log("observer vs mediator vs pubsub ok");
ObserverMediatorPub-Sub
DirectionOne subject to many observersMany peers to many peers, via a hubMany publishers to many subscribers, via topics
Who holds the logicEach observer decides how to reactThe mediator decides who hears whatNobody; the broker just routes
CouplingObservers know the subjectPeers know the mediatorBoth know only topic names
Typical exampleUI binding, model change listeners, EventEmitterChat room, air traffic control, a form dialogDomain events, message brokers, Kafka topics

The test: does the sender keep a list of receivers? Observer. Does a central object contain rules about who talks to whom? Mediator. Do sender and receiver share nothing but a topic name? Pub-Sub. The Observer and Mediator pages each go deeper, and the event bus patterns page covers pub-sub across services.

Command vs Strategy

Both wrap behaviour in an object you can pass around. The difference is what the object represents.

  • A Strategy is how to do something. It's a policy, usually stateless, that the context calls whenever it needs the algorithm. You hold one and use it many times.
  • A Command is a specific request to do something: "add 2 apples to cart 17". It carries its own arguments and receiver, and it exists so the request can be stored, queued, logged, retried or undone. You create one per action.
from dataclasses import dataclass, field
from typing import Callable, Protocol

# Strategy: HOW tax is computed. One policy, reused for every calculation.
TaxPolicy = Callable[[int], int]


def flat_ten_percent(cents: int) -> int:
    return cents // 10


def tax_free(cents: int) -> int:
    return 0


@dataclass
class Cart:
    tax: TaxPolicy
    items: dict[str, int] = field(default_factory=dict)  # sku -> price in cents

    def total(self) -> int:
        subtotal = sum(self.items.values())
        return subtotal + self.tax(subtotal)


# Command: ONE request, with its own data, that can be undone and kept in history.
class Command(Protocol):
    def execute(self) -> None: ...
    def undo(self) -> None: ...


@dataclass
class AddItem:
    cart: Cart
    sku: str
    price: int

    def execute(self) -> None:
        self.cart.items[self.sku] = self.price

    def undo(self) -> None:
        del self.cart.items[self.sku]


class History:
    def __init__(self) -> None:
        self._done: list[Command] = []

    def run(self, command: Command) -> None:
        command.execute()
        self._done.append(command)

    def undo(self) -> None:
        self._done.pop().undo()


cart = Cart(tax=flat_ten_percent)
history = History()
history.run(AddItem(cart, "apple", 300))
history.run(AddItem(cart, "pear", 700))
assert cart.total() == 1100
history.undo()
assert cart.total() == 330

cart.tax = tax_free          # swapping the strategy changes how, not what
assert cart.total() == 300
print("command vs strategy ok")

The test: would you ever put it in a list to undo, replay or send to a worker later? Command. Is it a pluggable way of computing something, called again and again? Strategy. A command's execute can use a strategy; they sit at different levels. The Command page builds full undo and redo stacks.

Template Method vs Strategy

Both let you vary steps of an algorithm. The difference is inheritance versus composition, and that difference has real consequences.

  • Template Method puts the skeleton in a base class method and lets subclasses override specific steps. The variation is fixed at compile time by choosing a subclass, and each subclass can only vary in the ways the base class allows.
  • Strategy puts the varying part behind an interface that the context holds. The variation can be chosen at runtime, combined with other strategies, and tested on its own.
import java.util.*;
import java.util.stream.*;

public class TemplateVsStrategy {
    // ---- Template Method: the skeleton is fixed in the base class, steps are overridden
    abstract static class ReportExporter {
        final String export(List<Integer> rows) {               // final: the skeleton can't change
            return header() + rows.stream().map(this::row).collect(Collectors.joining()) + footer();
        }
        protected abstract String header();
        protected abstract String row(int value);
        protected String footer() { return ""; }                 // a hook with a default
    }
    static final class CsvExporter extends ReportExporter {
        protected String header() { return "value\n"; }
        protected String row(int v) { return v + "\n"; }
    }
    static final class HtmlExporter extends ReportExporter {
        protected String header() { return "<ul>"; }
        protected String row(int v) { return "<li>" + v + "</li>"; }
        protected String footer() { return "</ul>"; }
    }

    // ---- Strategy: the varying part is an object the exporter holds
    interface RowFormat { String header(); String row(int v); String footer(); }
    record Exporter(RowFormat format) {
        String export(List<Integer> rows) {
            return format.header() + rows.stream().map(format::row).collect(Collectors.joining()) + format.footer();
        }
    }
    static final RowFormat CSV = new RowFormat() {
        public String header() { return "value\n"; }
        public String row(int v) { return v + "\n"; }
        public String footer() { return ""; }
    };

    public static void main(String[] args) {
        List<Integer> rows = List.of(1, 2);
        assert new CsvExporter().export(rows).equals("value\n1\n2\n");
        assert new HtmlExporter().export(rows).equals("<ul><li>1</li><li>2</li></ul>");

        Exporter csv = new Exporter(CSV);
        assert csv.export(rows).equals(new CsvExporter().export(rows));
        Exporter swapped = new Exporter(new RowFormat() {        // chosen at runtime, no subclass
            public String header() { return "["; }
            public String row(int v) { return v + ";"; }
            public String footer() { return "]"; }
        });
        assert swapped.export(rows).equals("[1;2;]");
        System.out.println("template vs strategy ok");
    }
}
Template MethodStrategy
MechanismInheritance, overriding stepsComposition, holding an interface
ChosenWhen you pick the subclassAt runtime, or by configuration
Unit of variationIndividual steps inside one skeletonThe whole algorithm, or a step as a separate object
Testability of a stepNeeds a subclassThe strategy is tested alone
Fits bestFrameworks with fixed lifecycles (test setup and teardown, request handling)Business policies that change or combine

The test: if you'd need two subclasses to vary two steps independently (CSV-to-file, CSV-to-S3, HTML-to-file, HTML-to-S3), Template Method is about to give you a subclass explosion, and Strategy (one object per varying step) is the better fit. If the skeleton is truly fixed and the steps vary together, Template Method is simpler. See the Template Method page.

Composite vs Decorator

Both use recursive composition: an object holds another object of the same interface. The difference is how many children, and why.

  • Composite holds many children and represents a part-whole tree. Its methods usually aggregate over the children (total size, render all, count).
  • Decorator holds exactly one wrapped object and adds behaviour around it. Its methods delegate and embellish.
interface Shape {
  area(): number;
  describe(): string;
}

class Rect implements Shape {
  constructor(private readonly w: number, private readonly h: number) {}
  area() {
    return this.w * this.h;
  }
  describe() {
    return `rect ${this.w}x${this.h}`;
  }
}

// Composite: many children, the result aggregates them.
class Group implements Shape {
  constructor(private readonly children: Shape[]) {}
  area() {
    return this.children.reduce((sum, c) => sum + c.area(), 0);
  }
  describe() {
    return `group(${this.children.map((c) => c.describe()).join(", ")})`;
  }
}

// Decorator: exactly one wrapped shape, behaviour added around it.
class Labelled implements Shape {
  constructor(private readonly inner: Shape, private readonly label: string) {}
  area() {
    return this.inner.area(); // unchanged
  }
  describe() {
    return `${this.label}: ${this.inner.describe()}`; // embellished
  }
}

const scene = new Group([new Rect(2, 3), new Labelled(new Group([new Rect(1, 1), new Rect(1, 2)]), "icons")]);
if (scene.area() !== 9) throw new Error("composite area");
if (scene.describe() !== "group(rect 2x3, icons: group(rect 1x1, rect 1x2))") throw new Error(scene.describe());
console.log("composite vs decorator ok");

The test: count the children. Many children whose results combine, Composite. One wrapped object whose behaviour is extended, Decorator. They nest happily, as the example shows: a decorated group inside a group. The Composite and Decorator pages cover each in depth.

Other pairs worth a sentence

  • Adapter vs Bridge. Both put an interface between two sides. An Adapter is applied after the fact to make existing incompatible code fit. A Bridge is designed up front so two hierarchies can vary independently.
  • Proxy vs Facade. A proxy has the same interface as one object. A facade has a new interface over several.
  • Memento vs Command for undo. Command undoes by running the inverse operation, which is cheap but must be written per command. Memento undoes by restoring a snapshot, which is generic but costs memory. Large editors often combine them: commands for most edits, snapshots at checkpoints.
  • Visitor vs Iterator. Iterator decides the order you see elements in. Visitor decides what you do to each element, by type. A tree walker often uses both.
  • Chain of Responsibility vs Decorator. Both form a chain of wrappers. In a chain, any link may stop the request and handle it. In a decorator stack, every layer normally passes the call through.
  • Specification vs Strategy. A specification is a strategy whose job is a yes/no answer, with the added ability to combine with and, or and not.
  • Flyweight vs Singleton vs Object Pool. Flyweight shares many immutable instances keyed by their state. Singleton has one instance. A pool lends out mutable instances and takes them back.

How to justify a pattern in an interview

Interviewers don't award points for naming patterns. They award points for showing that a design decision followed from a requirement and that you know what it costs. The scoring page lists pattern-dropping (naming patterns without tying them to requirements) as a red flag, and the over-patterning section of the mistakes page shows what that looks like in code. A pattern you can't justify costs you more than no pattern.

A five-step script

When you introduce a pattern, say these five things, in this order:

  1. The requirement. Quote the interviewer or the requirement you wrote down. "You said pricing differs for weekdays, weekends and events, and that new schemes get added."
  2. The axis of change. Name what varies, independently of what. "So the fee calculation varies, and it varies independently of how we allocate spots."
  3. The smallest structure. Describe the interface, not the pattern name. "I'll put it behind a PricingPolicy interface with one method, fee(ticket, exitTime), and give the lot one at construction."
  4. The name, last. "That's the Strategy pattern." Naming it after the reasoning shows the pattern came from the problem, not from a checklist.
  5. The cost and the rejected alternative. "It costs one interface and a class per scheme. The alternative is a switch in ParkingLot, which is fine for two schemes but means editing the lot for every new one."

Here it is end to end, as you might say it:

"Since pricing schemes change independently of the rest of the lot, and you mentioned new ones get added, I'll pull fee calculation behind a PricingPolicy interface. The lot gets one in its constructor. That's Strategy. It's one extra interface. If we only ever had hourly pricing, I'd just keep a method on the lot."

That last sentence is what separates a strong answer from a memorised one: it shows you know the condition under which you wouldn't do this.

Phrases that land well and phrases that don't

Instead of...Say...Why
"I'll use the Strategy pattern here." (first sentence)"Pricing varies independently, so I'll put it behind an interface. That's Strategy."Reasoning first, label second
"It's best practice.""It means adding a scheme doesn't touch the lot."Concrete benefit beats appeal to authority
"For extensibility.""You said new vehicle types are coming. This is where they'd plug in."Extensibility for what? Tie it to a stated change
"I'll make it a singleton so there's only one.""There's one lot per process, so I'll create one and pass it in."Same outcome, without global state
"I'll add a factory, an abstract factory and a builder.""Construction is simple, so plain constructors for now."Restraint is a signal too
"This follows SOLID.""This keeps the lot closed to pricing changes, the open-closed idea."Name the specific principle and how

When the interviewer pushes back

"Why not just an if statement?" Agree where it's fair. "For two fixed cases, an if is clearer. I'm reaching for the interface because you said schemes get added, and because it lets me test pricing without building a lot." If they then say "assume it's only ever two", switch to the if without arguing. Showing you can drop a pattern is as valuable as showing you can apply one.

"Isn't that over-engineering?" Give the cost honestly and offer the cheaper version. "It's one interface and two small classes. If you'd rather, I'll start with a method and extract the interface when the third scheme arrives."

"What other pattern could you use here?" Have the look-alike ready: "State would fit if the lot's pricing changed by itself as it filled up. Here the caller chooses the scheme, so Strategy." The comparisons above are the usual candidates.

"What does this pattern cost?" Every pattern adds indirection (a reader has to jump to find the behaviour), more types, and the risk of the wrong abstraction. Name the one that matters most in context.

When to bring patterns up at all

In a 45-minute round, patterns belong after you have entities, relationships and the core flow (see the interview framework). Introduce one at the moment a requirement creates variation, not in a list at the start ("I'll use Factory, Strategy and Observer"). Two or three well-justified patterns in a parking lot or vending machine design is plenty. Ten is a warning sign.

When not to use any pattern

Patterns cost something every time: an extra interface, another file, another jump for the reader, and an abstraction that has to be right. When the variation they protect against never arrives, you pay that cost for nothing. Some guidelines for when to write the plain code instead:

There is one variant and no stated second. An interface with one implementation and no requirement for another is a guess about the future. Write the concrete class. Extracting an interface later is a small, safe refactoring, especially in a statically typed language where the compiler finds every caller.

The variation is data, not behaviour. If three "strategies" differ only in a number (a 5%, 10% or 15% discount), you need a field, not three classes. Reach for polymorphism when the code differs, not the constants.

The language already does it. Many patterns were written for languages that lacked features modern ones have. Using the feature is not "skipping the pattern"; it is the pattern, with less ceremony.

PatternOften replaced by
StrategyA function or lambda parameter
Command (without undo)A closure, a Runnable or a callback
Template MethodA higher-order function that takes the varying steps
IteratorGenerators (yield), Java streams, for...of
ObserverEventEmitter, EventTarget, signals, RxJS
VisitorSealed types plus pattern matching (Java 21 switch, TypeScript discriminated unions, Python match)
BuilderKeyword and default arguments (Python), object literals (TypeScript), records with with-style copies
Prototypecopy.deepcopy, structuredClone, record copy constructors
SingletonA module-level instance, or one instance passed in by the composition root
FlyweightString interning, Integer.valueOf caching, enums
Null Object (in one place)Optional chaining ?. or an Optional with a default

The code is small and will stay small. A 200-line script, a one-off migration or a CLI with three commands does not need extension points. Patterns pay off in code that many people change over a long time.

You can't name the axis of change. If the honest answer to "what varies here?" is "I don't know, but something might", don't add a pattern. Wait for the second case. A common rule of thumb is to tolerate duplication until the third occurrence, because by then you know what actually varies and the abstraction can follow the real shape instead of a guessed one.

The pattern hides something important. A Null Object for a payment gateway, a Proxy that makes a network call look like a field read, an Observer chain that makes the order of side effects impossible to see. Indirection that hides failure modes or costs is worse than none.

Here is the over-patterned version of a two-option requirement next to the plain one. Both pass the same check.

// Over-patterned: an interface, two classes, a factory and a registry, for two fixed options.
interface ShippingStrategy {
  cost(kg: number): number;
}
class StandardShipping implements ShippingStrategy {
  cost(kg: number) {
    return 500 + 100 * kg;
  }
}
class ExpressShipping implements ShippingStrategy {
  cost(kg: number) {
    return 1500 + 200 * kg;
  }
}
class ShippingStrategyFactory {
  private static readonly registry: Record<string, () => ShippingStrategy> = {
    standard: () => new StandardShipping(),
    express: () => new ExpressShipping(),
  };
  static create(kind: string): ShippingStrategy {
    const make = this.registry[kind];
    if (!make) throw new Error(`unknown shipping ${kind}`);
    return make();
  }
}

// Plain: the requirement is two fixed options, so say exactly that.
type Shipping = "standard" | "express";
function shippingCost(kind: Shipping, kg: number): number {
  return kind === "express" ? 1500 + 200 * kg : 500 + 100 * kg;
}

for (const kind of ["standard", "express"] as const) {
  if (ShippingStrategyFactory.create(kind).cost(3) !== shippingCost(kind, 3)) throw new Error(kind);
}
console.log("same answers, a fifth of the code");

The plain version is also safer: the TypeScript compiler rejects shippingCost("overnight", 3), while the factory only finds the typo at runtime. If a third, fourth and fifth shipping option arrive, each with its own logic, the strategy version starts to earn its keep, and converting is a ten-minute change.

Signs a pattern should be removed

Patterns can also outlive their reason. Candidates for inlining back into plain code:

  • An interface that has had one implementation for a year.
  • A factory whose create method has one branch.
  • A decorator that every caller wraps around the same object, so it is never actually optional.
  • An observer with exactly one listener, registered right next to the subject.
  • A visitor over a type hierarchy that keeps gaining types (every new type edits every visitor, the opposite of what Visitor is good for).

Deleting an unused abstraction is a design improvement, and saying so in an interview ("I'd inline this; the variation never came") is a mature answer.

Interview questions

  1. "How do you decide which design pattern to use?" Start from what varies. Name the thing that changes independently of the rest, check whether a requirement says it will change, then pick the pattern that draws a boundary around it. If nothing varies, use no pattern.

  2. "Strategy and State have the same class diagram. What's the difference?" Who chooses the implementation. In Strategy the client picks it and it stays put. In State the object switches implementations itself as events arrive, and the states know their successors.

  3. "Decorator or Proxy: which is a caching wrapper?" Either, depending on intent. If the point is to add caching as an optional, stackable behaviour, call it a decorator. If the point is to control access to an expensive or remote object, call it a proxy. The code can be identical; the name communicates why it exists.

  4. "When would you choose Abstract Factory over Factory Method?" When products come in families that must be used together, such as matching UI widgets or one cloud provider's clients. Factory Method chooses one product; Abstract Factory guarantees a consistent set.

  5. "Observer, Mediator or Pub-Sub for a chat application?" Mediator for the in-process room logic (who sees whose message, mutes, moderation). Pub-Sub once messages cross servers, so that sender and receiver connections share only a channel name. Observer inside a client, so views react to model changes.

  6. "Template Method or Strategy for an export pipeline with different formats and destinations?" Strategy, one per varying step (format and destination). Template Method would need a subclass per combination. Template Method fits when the skeleton is fixed and only one dimension varies.

  7. "What pattern would you use here?" (about simple code) It's fine to say none. Explain what would have to change for a pattern to pay off: "If you add a third payment method with its own validation, I'd extract a strategy."

  8. "Which patterns do modern language features make less necessary?" Strategy and Command become functions and closures, Iterator becomes generators, Visitor becomes sealed types with pattern matching, Builder becomes keyword arguments in many languages, and Singleton becomes a module-level instance or dependency injection. The intent survives; the boilerplate shrinks.

  9. "What's the cost of a pattern?" Indirection (readers jump to find behaviour), more types to maintain, and the risk of abstracting along the wrong axis, which is harder to undo than duplication.

  10. "Give an example of a pattern you'd remove." A factory with one product, an interface with one implementation and no planned second, or a visitor over a type hierarchy that keeps growing. Inlining those simplifies the code without losing anything.

Further reading