Software ArchitectureVol. 13 · Part XIII
0 / 0

Shelves / Software Architecture

SA·137

Design Patterns

Reusable solutions to recurring design problems, each explained by intent, forces, structure, code across paradigms and when not to use it: creational (Factory Method, Abstract Factory, Builder, Prototype, plus Singleton's pitfalls), structural (Adapter, Decorator, Facade, Composite, Proxy), behavioural (Strategy, Observer, State, Command, Template Method, Chain of Responsibility), and modern patterns (dependency injection, middleware, pipelines, functional composition), showing how many classic patterns collapse into functions, closures, sum types and traits in modern languages.

34 topics · ~43 min read · 31-question quiz
Updated Suggest a correction

Start here: named solutions to problems that keep coming back

A design pattern is a reusable answer to a design problem that keeps recurring, with a name so people can discuss it quickly. "Wrap the client in a retrying decorator" or "pick the pricing rule with a strategy" says in four words what would otherwise take a paragraph. Patterns aren't goals; each solves a specific tension (its forces) and adds indirection, so you use one when its problem is actually present.

Decorator: add behaviour by wrapping

The menu comes from a supplier's API that fails 30% of the time and takes 2 ms per call. Each concern is a small class that implements the same get(day) method and wraps another one:

Python
src = Metrics(Cache(Retry(FlakyProvider())))

1,000 menu requests spread over 7 days:

Text
plain provider                     success 69.7%   provider calls 1,000   2.18 s
Retry(provider)                    success 98.2%   provider calls 1,370   3.02 s
Cache(Retry(provider))             success 99.9%   provider calls    12   0.03 s
Metrics(Cache(Retry(provider)))    success 99.9%   provider calls    13   0.03 s

Retrying raised success from 70% to 98% at the cost of 37% more calls; caching on top cut calls to the supplier from 1,370 to 12 (one per day, plus retries) and time from 3 s to 0.03 s; metrics counted outcomes without the other classes knowing. None of the four classes knows about the others, and each can be tested alone. Ordering matters: Retry(Cache(…)) would retry cache lookups, and Cache(Metrics(…)) would count only cache misses.

What indirection costs

Patterns add layers. Measured per call:

Text
Python, pass-through decorator layers:   0 → 47 ns   1 → 79 ns   3 → 201 ns   6 → 342 ns
Go, direct call 2.30 ns; through an interface 2.54 ns; two implementations mixed 2.36 ns; a switch 2.40 ns

Each Python layer adds roughly 50 ns, and in Go the compiler made interface dispatch practically free. Next to a 2 ms network call, six layers are 0.02% of the time. The real cost of patterns is the reader's time: every layer is another file to open to find out what a call does. Use a pattern when the problem it solves exists, not because it might one day.

The patterns you'll meet most

Pattern Problem it solves Everyday example
Strategy choose one of several algorithms at run time pricing rules, payment methods
Decorator add behaviour around an object without changing it retry, cache, metrics, logging wrappers
Adapter make an existing interface fit the one you need wrapping a supplier SDK behind your MenuSource
Factory / Builder construct complex or varied objects cleanly building an order with many optional parts
Observer / pub-sub notify many interested parties of a change order placed → kitchen, SMS, analytics
Facade one simple entry point to a complicated subsystem a module's public API (chapter 140)
State behaviour that depends on an explicit state order lifecycle: placed → cooking → ready

How deep to go in design patterns

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Name the common patterns and recognise them in code
L2 Apply Strategy, Decorator, Adapter, Factory, Observer and State where their problems appear
L3 Explain each pattern's forces, trade-offs and functional equivalents
L4 Spot misapplied patterns and refactor towards or away from them
L5 Choose patterns consistently across a codebase's architecture
L6 Teach a shared pattern language and keep it from turning into ceremony

What patterns are (and aren't)

A design pattern is a named, reusable solution to a problem that recurs in a context, with known trade-offs. The idea comes from architect Christopher Alexander (A Pattern Language, 1977); the 1994 book Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (the Gang of Four, GoF) catalogued 23 patterns for object-oriented code.

Patterns give teams a shared vocabulary ("wrap it in a decorator", "this is a strategy") and capture design wisdom. They are not:

  • Templates to apply everywhere: a pattern adds structure and indirection, which costs readability unless it solves a real problem.
  • Language-independent in their form: many GoF patterns exist to work around missing features in 1990s C++/Smalltalk. In languages with first-class functions, closures, sum types, traits, generics and modules, several collapse into a few lines (Peter Norvig observed in 1996 that 16 of 23 GoF patterns are invisible or simpler in dynamic languages).

For each pattern below: intent, when to use, code, modern equivalent, and when not to.

creationalFactory MethodAbstract FactoryBuilderPrototype(Singleton: careful) structuralAdapterDecoratorFacadeCompositeProxy behaviouralStrategyObserverStateCommandTemplate MethodChain of Resp. moderndependency inj.middlewarepipelinecomposition functional lens: functions · closures · sum types · traits · composition
The patterns in this chapter grouped by purpose. Creational patterns control how objects are created; structural patterns compose objects and interfaces; behavioural patterns distribute responsibilities and algorithms; modern patterns organise dependencies and request processing. Many map directly onto functional constructs such as higher-order functions, closures, sum types and function composition.

Creational patterns

Factory Method and simple factories

Intent: create objects without the caller specifying the concrete class; centralise creation logic (choosing an implementation, validating, caching).

Variants:

  • Static factory method: Duration.ofSeconds(30), List.of(...), Money.of(amount, currency): descriptive names, can return cached instances or subtypes, can validate (smart constructors).
  • Factory Method (GoF): a superclass defines createX(); subclasses override it to decide the concrete product.
  • Simple factory function: newStorage(config) Storage choosing an implementation from configuration.
// Static factory + validation (smart constructor); constructor stays private
public final class Email {
    private final String value;
    private Email(String value) { this.value = value; }

    public static Email of(String raw) {
        String v = raw.strip().toLowerCase(Locale.ROOT);
        if (!v.matches("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")) throw new IllegalArgumentException("invalid email");
        return new Email(v);
    }
    public String value() { return value; }
}

// Factory choosing an implementation from configuration
public static BlobStore blobStore(StorageConfig cfg) {
    return switch (cfg.kind()) {
        case S3    -> new S3BlobStore(cfg.bucket());
        case GCS   -> new GcsBlobStore(cfg.bucket());
        case LOCAL -> new FileBlobStore(Path.of(cfg.dir()));
    };
}

When not to: wrapping trivial new calls in factories with no logic adds indirection; just construct the object.

Abstract Factory

Intent: create families of related objects that must be used together, without specifying concrete classes: a UI theme (buttons, text fields, dialogs for macOS vs Windows), a cloud provider family (blob store + queue + secrets for AWS vs GCP), a database dialect (connection, query builder, migration tool).

Kotlin
// Kotlin: an abstract factory for a cloud "family" chosen once at startup
interface CloudFactory {
    fun blobStore(): BlobStore
    fun queue(name: String): MessageQueue
    fun secrets(): SecretStore
}

class AwsFactory(private val region: String) : CloudFactory {
    override fun blobStore() = S3BlobStore(region)
    override fun queue(name: String) = SqsQueue(region, name)
    override fun secrets() = AwsSecretsManager(region)
}

class LocalFactory : CloudFactory {           // for development and tests
    override fun blobStore() = FileBlobStore(Path("/tmp/blobs"))
    override fun queue(name: String) = InMemoryQueue(name)
    override fun secrets() = EnvSecretStore()
}

fun app(factory: CloudFactory) = App(factory.blobStore(), factory.queue("orders"), factory.secrets())

Modern equivalent: a DI container profile/configuration (Spring profiles, Guice modules) or a struct of constructors chosen at the composition root. When not to: if there's only one family, it's speculative.

Builder

Intent: construct complex objects step by step, especially with many optional parameters, without telescoping constructors (new Pizza(size, cheese, null, null, true, false, ...)), and produce an immutable result validated as a whole.

// Java: builder producing an immutable request; validation in build()
public final class HttpRequestSpec {
    private final URI uri; private final String method; private final Duration timeout;
    private final Map<String, String> headers;

    private HttpRequestSpec(Builder b) {
        this.uri = b.uri; this.method = b.method; this.timeout = b.timeout; this.headers = Map.copyOf(b.headers);
    }
    public static Builder to(URI uri) { return new Builder(uri); }

    public static final class Builder {
        private final URI uri; private String method = "GET";
        private Duration timeout = Duration.ofSeconds(5); private final Map<String, String> headers = new HashMap<>();
        private Builder(URI uri) { this.uri = Objects.requireNonNull(uri); }
        public Builder method(String m) { this.method = m; return this; }
        public Builder timeout(Duration t) { this.timeout = t; return this; }
        public Builder header(String k, String v) { headers.put(k, v); return this; }
        public HttpRequestSpec build() {
            if (timeout.isNegative() || timeout.isZero()) throw new IllegalStateException("timeout must be > 0");
            return new HttpRequestSpec(this);
        }
    }
}
var spec = HttpRequestSpec.to(URI.create("https://api.example.com/orders"))
    .method("POST").timeout(Duration.ofSeconds(2)).header("Idempotency-Key", key).build();

When not to: languages with named/default arguments (Kotlin, Python, C#, Swift, Scala) rarely need classic builders. Use builders for genuinely complex, staged construction (query builders, test data builders like anOrder().paid().build()).

Prototype

Intent: create new objects by copying an existing instance (a prototype), useful when construction is expensive or when you want variations of a configured template.

  • Java's Cloneable is widely considered broken (shallow copy, no constructor, checked exception); prefer copy constructors or with-style methods on records.
  • Kotlin data class copy(), C# record with expressions, Rust #[derive(Clone)], Python copy.deepcopy/dataclasses.replace, JavaScript structuredClone or object spread.
  • JavaScript's object model is literally prototype-based (objects delegate to prototype objects).
C#
// C#: records with non-destructive mutation ("with") are the modern prototype
public record Theme(string Primary, string Background, int FontSize);
var dark = new Theme("#8cc1f0", "#0f141b", 14);
var largeDark = dark with { FontSize = 18 };      // copy with one change

When not to: deep copies of object graphs with shared references and cycles are error-prone; immutable values often eliminate the need.

A note on Singleton

Singleton (one instance, globally accessible) is the most criticised GoF pattern: it's global mutable state in disguise, hides dependencies, complicates testing (tests share state; can't substitute fakes), and causes initialisation-order and concurrency bugs.

Prefer: create one instance at the composition root and inject it (DI containers manage singleton scope without global access). Genuine process-wide singletons (a logger, a metrics registry) are acceptable when stateless or thread-safe, and even then, injecting them is better for tests.

Structural patterns

Adapter

Intent: make an existing interface usable where a different one is expected, by translating calls. Essential at boundaries (chapter 135): wrapping third-party SDKs, legacy systems or external APIs behind your own port.

// Domain port in our language; adapter translates to a vendor SDK
public interface ExchangeRates {
    BigDecimal rate(Currency from, Currency to, LocalDate on);
}

final class AcmeFxAdapter implements ExchangeRates {
    private final AcmeFxClient client;                              // vendor SDK
    AcmeFxAdapter(AcmeFxClient client) { this.client = client; }

    @Override
    public BigDecimal rate(Currency from, Currency to, LocalDate on) {
        AcmeQuote q = client.getQuote(from.getCurrencyCode() + to.getCurrencyCode(), on.toString());
        if (q.status() != AcmeStatus.OK) throw new RatesUnavailable(from, to, on);
        return new BigDecimal(q.midRate());                          // vendor's string → our type
    }
}

Related: the anti-corruption layer (chapter 138) is a large-scale adapter protecting a domain model from another system's model.

Decorator

Intent: attach additional behaviour to an object dynamically, by wrapping it in an object with the same interface, without changing the original or subclassing. Ideal for cross-cutting concerns: caching, logging, metrics, retries, authorisation, transactions.

MetricsRepo implements ProductRepository RetryRepo implements ProductRepository CachingRepo implements ProductRepository PostgresProductRepository call passes through each layer · same interface everywhere · compose in any order
Decorators wrap a component behind the same interface. A call passes through the outer decorators (metrics, retry, caching) before reaching the real repository, and the result returns back through them. Each decorator adds one behaviour, can be added or removed independently, and the caller only sees the interface.
// Java: caching decorator over a repository interface
final class CachingProductRepository implements ProductRepository {
    private final ProductRepository inner;
    private final Cache<ProductId, Product> cache;
    CachingProductRepository(ProductRepository inner, Cache<ProductId, Product> cache) {
        this.inner = inner; this.cache = cache;
    }
    @Override public Optional<Product> find(ProductId id) {
        Product cached = cache.getIfPresent(id);
        if (cached != null) return Optional.of(cached);
        Optional<Product> p = inner.find(id);
        p.ifPresent(v -> cache.put(id, v));
        return p;
    }
    @Override public void save(Product p) { inner.save(p); cache.invalidate(p.id()); }
}

ProductRepository repo = new MetricsProductRepository(
    new CachingProductRepository(new JdbcProductRepository(ds), Caffeine.newBuilder().maximumSize(10_000).build()),
    meterRegistry);

Java's java.io streams (new BufferedReader(new InputStreamReader(...))), Spring's AOP proxies for @Transactional/@Cacheable, and Python's @functools.lru_cache are decorators. When not to: deep stacks of decorators can obscure behaviour and ordering; document the composition in one place (the composition root).

Facade

Intent: provide a simple interface to a complex subsystem, so clients don't need to know its many parts. A facade reduces coupling between clients and subsystem internals (a deep module, chapter 135).

Python
# Facade: one call hides the video pipeline's many collaborators
class VideoPublishing:
    def __init__(self, storage, transcoder, thumbnails, cdn, catalogue, notifier):
        self._storage, self._transcoder, self._thumbs = storage, transcoder, thumbnails
        self._cdn, self._catalogue, self._notifier = cdn, catalogue, notifier

    def publish(self, upload_id: str, owner: str) -> VideoId:
        raw = self._storage.raw(upload_id)
        renditions = self._transcoder.transcode(raw, profiles=["1080p", "720p", "480p"])
        thumb = self._thumbs.generate(raw)
        urls = self._cdn.publish(renditions + [thumb])
        video_id = self._catalogue.register(owner, urls)
        self._notifier.video_published(owner, video_id)
        return video_id

Application services in layered/hexagonal architectures, SDK clients, and API gateways/BFFs are facades. When not to: a facade that grows to expose every subsystem operation becomes a god object; keep it focused on common use cases and let advanced clients use the subsystem directly.

Composite

Intent: treat individual objects and compositions of objects uniformly through a common interface, forming tree structures: file systems (files and directories), UI component trees, organisation charts, expression trees, pricing rules composed of rules, permission groups.

// Rust: composite as a recursive enum — the idiomatic functional/sum-type form
pub enum PriceRule {
    Percent(u8),
    Fixed(Money),
    All(Vec<PriceRule>),          // apply all, in order
    BestOf(Vec<PriceRule>),       // pick the largest discount
}

impl PriceRule {
    pub fn discount(&self, subtotal: Money) -> Money {
        match self {
            PriceRule::Percent(p) => subtotal * (*p as i64) / 100,
            PriceRule::Fixed(m) => (*m).min(subtotal),
            PriceRule::All(rules) => rules.iter().fold(Money::ZERO, |acc, r| acc + r.discount(subtotal - acc)),
            PriceRule::BestOf(rules) => rules.iter().map(|r| r.discount(subtotal)).max().unwrap_or(Money::ZERO),
        }
    }
}

Proxy

Intent: provide a surrogate that controls access to another object with the same interface: lazy loading (virtual proxy), access control (protection proxy), remote calls (remote proxy/RPC stubs), caching, logging, rate limiting.

Differences: a decorator adds behaviour; a proxy controls access (often the same mechanics). Examples everywhere:

  • ORM lazy-loading proxies (Hibernate entity proxies loading associations on first access, the source of N+1 surprises).
  • gRPC/RMI client stubs (remote proxies).
  • Spring AOP and Java java.lang.reflect.Proxy dynamic proxies; JavaScript Proxy objects.
  • Network proxies, service-mesh sidecars and API gateways at the infrastructure scale.
TypeScript
// JavaScript Proxy: read-only protection proxy around a config object
const readonly = <T extends object>(target: T): T =>
  new Proxy(target, {
    set() { throw new TypeError("config is read-only"); },
    deleteProperty() { throw new TypeError("config is read-only"); },
  });
const config = readonly({ region: "ap-south-1", retries: 3 });

Behavioural patterns

Strategy

Intent: define a family of interchangeable algorithms, encapsulate each, and let clients choose at runtime: pricing rules, routing algorithms, compression codecs, retry policies, sorting comparators, authentication methods.

// Java: a strategy is just a functional interface; lambdas are strategies
@FunctionalInterface
interface ShippingCost { Money cost(Parcel p); }

ShippingCost flat    = p -> Money.inr(49);
ShippingCost byWeight = p -> Money.inr(20).times(Math.ceil(p.kg()));
ShippingCost freeOver = p -> p.value().compareTo(Money.inr(999)) >= 0 ? Money.zero() : byWeight.cost(p);

Map<ShippingTier, ShippingCost> strategies = Map.of(STANDARD, freeOver, EXPRESS, p -> byWeight.cost(p).times(2));
Money cost = strategies.get(order.tier()).cost(order.parcel());

When not to: if there's a single algorithm that never varies, inline it. With first-class functions, a separate class hierarchy for strategies is usually unnecessary.

Observer

Intent: when one object changes state, all its dependents are notified automatically (publish/subscribe within a process): UI data binding, domain events dispatched in-process, reactive streams, listeners and callbacks.

subjectobservers: [..]notify(event) EmailNotifier LoyaltyPoints AnalyticsTracker onEvent() same idea at larger scale: event bus → reactive streams → message brokers
Observer. Observers register with a subject; when the subject's state changes it notifies each registered observer through a common interface, without knowing their concrete types. The same idea scales up to in-process event buses, reactive streams, and out-of-process pub/sub messaging.
// Java: in-process domain events with Spring's ApplicationEventPublisher
public record OrderPlaced(OrderId orderId, CustomerId customerId, Money total) {}

@Service
class OrderService {
    private final ApplicationEventPublisher events;
    OrderService(ApplicationEventPublisher events) { this.events = events; }
    @Transactional
    public OrderId place(PlaceOrder cmd) {
        Order order = /* ... */;
        events.publishEvent(new OrderPlaced(order.id(), order.customerId(), order.total()));
        return order.id();
    }
}

@Component
class LoyaltyListener {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)   // only if the order committed
    void on(OrderPlaced e) { /* award points */ }
}

Pitfalls: memory leaks from observers never unsubscribed (lapsed listeners), unclear ordering and re-entrancy (an observer triggers another change during notification), error handling (one failing observer shouldn't break others), hidden control flow ("who reacts to this?"), and transactional boundaries (notify after commit, not before). Across processes, use messaging with outbox (Vol. 12 ch. 131).

State

Intent: let an object change its behaviour when its internal state changes, by representing each state explicitly; replaces sprawling conditionals on status flags. Order lifecycles, document workflows, connection protocols, UI wizards, game entities.

CREATED PAID SHIPPED DELIVERED CANCELLED REFUNDED pay ship deliver cancel refund SHIPPED → cancel:not a transition
An order state machine. Each state allows only certain transitions: a created order can be paid or cancelled; a paid order can be shipped or refunded; a shipped order can be delivered. Modelling states explicitly makes illegal transitions impossible to express rather than relying on scattered status checks.
// Rust typestate: each state is a type; illegal transitions don't compile
pub struct Order<S> { id: OrderId, total: Money, state: S }
pub struct Created; pub struct Paid { payment: PaymentId } pub struct Shipped { tracking: String }

impl Order<Created> {
    pub fn pay(self, payment: PaymentId) -> Order<Paid> { Order { id: self.id, total: self.total, state: Paid { payment } } }
    pub fn cancel(self) -> Cancelled { Cancelled { id: self.id } }
}
impl Order<Paid> {
    pub fn ship(self, tracking: String) -> Order<Shipped> { Order { id: self.id, total: self.total, state: Shipped { tracking } } }
}
// order.ship(...) on Order<Created> is a compile error: no such method.

For complex workflows (timers, retries, long-running), consider statechart libraries (XState for TypeScript, Spring Statemachine) or durable workflow engines (Vol. 12 ch. 131).

Command

Intent: encapsulate a request as an object (or value), so it can be queued, logged, retried, undone, scheduled, sent over the wire, or validated independently of its execution. Used in undo/redo editors, job queues, CQRS commands, transactional outbox messages, macro recording, GUI actions.

TypeScript
// Command objects with execute/undo: undo/redo stack in an editor
interface Command { execute(doc: Doc): void; undo(doc: Doc): void; label: string }

class InsertText implements Command {
  label = "Insert text";
  constructor(private pos: number, private text: string) {}
  execute(doc: Doc) { doc.insert(this.pos, this.text); }
  undo(doc: Doc) { doc.delete(this.pos, this.text.length); }
}

class History {
  private done: Command[] = []; private undone: Command[] = [];
  run(cmd: Command, doc: Doc) { cmd.execute(doc); this.done.push(cmd); this.undone = []; }
  undo(doc: Doc) { const c = this.done.pop(); if (c) { c.undo(doc); this.undone.push(c); } }
  redo(doc: Doc) { const c = this.undone.pop(); if (c) { c.execute(doc); this.done.push(c); } }
}

In functional languages a command can be a data value (an ADT variant) interpreted by a function, which makes commands serialisable and testable: data Command = Deposit Amount | Withdraw Amount. In service architectures, commands are messages (PlaceOrder) handled by command handlers (Vol. 12 ch. 131).

Template Method

Intent: define the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the overall structure. Examples: AbstractList in Java collections, test framework lifecycles (setUp/tearDown), Spring's JdbcTemplate historically (now mostly callback-based), framework hooks.

Java
// Template Method: the skeleton is fixed (final); subclasses fill in the steps
public abstract class ReportExporter {
    public final Path export(ReportQuery q) {            // template
        List<Row> rows = fetch(q);
        List<Row> filtered = rows.stream().filter(this::include).toList();
        byte[] bytes = render(filtered);
        return store(q.name(), bytes);
    }
    protected abstract List<Row> fetch(ReportQuery q);
    protected boolean include(Row r) { return true; }    // hook with default
    protected abstract byte[] render(List<Row> rows);
    private Path store(String name, byte[] bytes) { /* ... */ return Path.of(name); }
}

Modern equivalent: pass the varying steps as functions (strategy/callbacks) to a function that implements the skeleton, avoiding inheritance:

Go
// Go: the skeleton is a function; variable steps are function parameters
func Export(q Query, fetch func(Query) ([]Row, error), render func([]Row) ([]byte, error)) (string, error) {
    rows, err := fetch(q)
    if err != nil { return "", err }
    b, err := render(rows)
    if err != nil { return "", err }
    return store(q.Name, b)
}

When not to: deep template hierarchies create fragile base classes; prefer composition unless the framework requires subclassing.

Chain of Responsibility

Intent: pass a request along a chain of handlers; each handler either handles it, transforms it, or passes it on. Decouples senders from receivers and lets you compose processing steps: HTTP middleware, servlet filters, logging handlers, validation rules, approval workflows (manager → director → CFO by amount), exception handlers, event processors.

Java
// Approval chain: each approver handles within its limit or passes along
abstract class Approver {
    private Approver next;
    Approver then(Approver next) { this.next = next; return next; }
    Decision approve(Expense e) {
        if (canApprove(e)) return decide(e);
        if (next == null) return Decision.rejected("no approver for " + e.amount());
        return next.approve(e);
    }
    protected abstract boolean canApprove(Expense e);
    protected abstract Decision decide(Expense e);
}
// manager.then(director).then(cfo); manager.approve(expense)

The modern, ubiquitous form is middleware (below).

Modern patterns

Dependency injection

Dependency injection (DI) means a component receives its dependencies from outside rather than creating or looking them up. Combined with dependency inversion (chapter 136), it decouples business logic from infrastructure and makes code testable.

Forms:

  • Constructor injection (preferred): dependencies are required, explicit and immutable.
  • Method/parameter injection: pass a dependency to the function that needs it (functional style; Go's context-free explicit params).
  • Setter/field injection: optional dependencies; hides requirements; avoid for required ones.

Wiring happens at the composition root (main, application configuration):

  • Manual (pure) DI: write the wiring code yourself; clear and compile-checked; idiomatic in Go, Rust and many small services.
  • DI containers/frameworks: Spring (runtime reflection, or AOT processing for native images), Micronaut and Quarkus (build-time DI), Dagger/Hilt (compile-time code generation, Android), Guice, .NET Microsoft.Extensions.DependencyInjection, NestJS/InversifyJS (TypeScript), Google Wire (Go, compile-time code generation), FastAPI's Depends.
  • Functional DI: pass records/structs of functions, partial application, reader monads, or effect systems (ZIO environment, Effect-TS layers, Haskell's ReaderT/tagless final).
// Go: manual DI in main — the whole object graph is visible in one place
func main() {
    cfg := config.MustLoad()
    pool := mustPool(cfg.DatabaseURL)
    clock := realClock{}

    orders := postgres.NewOrderStore(pool)
    payments := stripeadapter.New(cfg.StripeKey)
    placeOrder := ordering.NewPlaceOrder(orders, payments, clock)

    api := httpapi.New(placeOrder)
    log.Fatal(http.ListenAndServe(cfg.Addr, api.Routes()))
}

Pitfalls: service locator (asking a global container for dependencies) hides dependencies; huge constructors signal SRP problems; container "magic" (classpath scanning, auto-configuration) can obscure what's wired, so keep the configuration understandable and verify the context in tests.

Middleware

Middleware is a chain of functions wrapping a handler, each able to act before and after the next one: authentication, logging, tracing, metrics, CORS, compression, rate limiting, panic recovery, request IDs, timeouts. It combines Decorator and Chain of Responsibility in functional form and is the backbone of web frameworks (Express, Koa, Go net/http, Rust tower/axum, ASP.NET Core, Django/Starlette, Ring in Clojure, Rack in Ruby, gRPC interceptors, Redux middleware).

recover request ID logging · tracing auth · rate limit handler request flows in → handler → response flows out through the same layers
A middleware chain wraps the handler like onion layers. A request passes inward through recovery, request ID, logging, authentication and rate limiting before reaching the handler; the response passes back outward through the same layers in reverse order, so each middleware can act both before and after the inner layers.
// Go net/http: middleware is func(http.Handler) http.Handler
type Middleware func(http.Handler) http.Handler

func Chain(h http.Handler, mws ...Middleware) http.Handler {
    for i := len(mws) - 1; i >= 0; i-- { h = mws[i](h) }     // first listed = outermost
    return h
}

func RequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-ID")
        if id == "" { id = uuid.NewString() }
        w.Header().Set("X-Request-ID", id)
        next.ServeHTTP(w, r.WithContext(withRequestID(r.Context(), id)))
    })
}

func Logging(log *slog.Logger) Middleware {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            start := time.Now()
            rec := &statusRecorder{ResponseWriter: w, status: 200}
            next.ServeHTTP(rec, r)                                   // call inner layers
            log.Info("request", "method", r.Method, "path", r.URL.Path, "status", rec.status,
                "duration_ms", time.Since(start).Milliseconds())     // after
        })
    }
}

handler := Chain(api, Recover, RequestID, Logging(logger), Auth(verifier))

Order matters (authentication before authorisation; recovery outermost; compression after body generation), so define the chain in one place.

Pipeline

A pipeline processes data through a sequence of stages, each transforming its input into output for the next: Unix pipes (grep | sort | uniq -c), stream APIs (Java Streams, Kotlin sequences, Rust iterators, LINQ, Python generators), ETL and data-processing jobs (Beam, Spark, Flink), compiler passes, CI/CD stages, and the pipes and filters architecture style (chapter 139).

// Java Streams: declarative pipeline, lazy until the terminal operation
Map<String, Long> topCustomers = orders.stream()
    .filter(o -> o.status() == PAID)
    .filter(o -> o.placedAt().isAfter(monthStart))
    .collect(groupingBy(o -> o.customerId().value(), summingLong(o -> o.total().minor())))
    .entrySet().stream()
    .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
    .limit(10)
    .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));

Design concerns for pipelines: back-pressure between stages, error handling (fail fast vs dead-letter bad items), parallelism per stage, ordering, and observability per stage.

Functional composition

Functions compose: given f: A → B and g: B → C, g ∘ f: A → C. Building behaviour by composing small, pure functions replaces many class-based patterns:

Classic pattern Functional equivalent
Strategy Pass a function
Template Method Higher-order function with step functions as parameters
Decorator Function wrapping a function (withRetry(withLogging(f)))
Command Data value (ADT) interpreted by a function
Observer Callback lists, streams (Rx), effect handlers
Chain of Responsibility / middleware Composition of Handler → Handler functions
Visitor Pattern matching over sum types (fold)
Factory Function returning a value; partial application
Builder Function with named/default arguments; fold over options
Iterator Lazy sequences, generators
Interpreter Algebraic data types + evaluation function
Haskell
-- Composition with (.) and pipelines with (&)
import Data.Function ((&))
import Data.Char (toLower, isAlphaNum)

slugify :: String -> String
slugify = collapseDashes . map (\c -> if isAlphaNum c then toLower c else '-')

summary :: [Order] -> Int
summary orders = orders & filter isPaid & map total & sum
TypeScript
// TypeScript: pipe for left-to-right composition of unary functions
const pipe = <T>(...fns: Array<(x: T) => T>) => (x: T) => fns.reduce((acc, f) => f(acc), x);
const normaliseEmail = pipe<string>((s) => s.trim(), (s) => s.toLowerCase());

Monadic composition extends this to functions with effects (Option, Result, Promise, IO): flatMap/and_then/>>= chain steps that may fail or be asynchronous, which is what Rust's ?, JavaScript's await and Haskell's do notation sugar over.

Choosing patterns wisely

  • Start from the problem, not the pattern: name the force (variation in algorithms? cross-cutting behaviour? complex construction? state-dependent behaviour?) and pick the lightest construct your language offers.
  • Prefer language features: functions, closures, sum types with exhaustive matching, traits/interfaces with default methods, records/data classes, named arguments, modules.
  • Refactor toward patterns when duplication or rigidity appears (Joshua Kerievsky, Refactoring to Patterns), rather than designing them in up front.
  • Name patterns in code and reviews when you do use them (CachingProductRepository, PaymentMethodRegistry), so readers recognise them.
  • Watch for pattern overload: AbstractSingletonProxyFactoryBean-style indirection is a cost.

Lab: composing decorators and measuring indirection

Python 3.13 and Go 1.24.7 on the lab machine. The flaky supplier is simulated (30% ConnectionError, 2 ms sleep, seeded random generator), so the figures are reproducible.

Experiment 1: a decorator stack

Python
class Retry(MenuSource):
    def __init__(self, inner, attempts=3): self.inner, self.attempts = inner, attempts
    def get(self, day):
        for i in range(self.attempts):
            try: return self.inner.get(day)
            except ConnectionError:
                if i == self.attempts - 1: raise
Composition Success Supplier calls Time
provider 69.7% 1,000 2.18 s
Retry(provider) 98.2% 1,370 3.02 s
Cache(Retry(provider)) 99.9% 12 0.03 s
Metrics(Cache(Retry(provider))) 99.9% 13 0.03 s

Expected success with 3 attempts: 1 − 0.3³ = 97.3%; measured 98.2%. The 0.1% failures in the cached runs are first fetches of a day where all three attempts failed. Python's function decorators (@retry, @lru_cache), Java's dynamic proxies and Spring AOP, Go's http.RoundTripper wrappers and middleware chains in every web framework are all this pattern. Resilience libraries (Resilience4j, Polly, tenacity) are decorator collections.

Experiment 2: the cost of a layer

Layers (Python) ns per call
0 47
1 79
3 201
6 342
Go call style (go test -bench, 2×10⁸ iterations) ns/op
direct method 2.302
through an interface 2.544
interface, two implementations alternating 2.363
switch on a kind field 2.399

The Go numbers are all within noise of each other: the compiler devirtualised or inlined, and the work per call dominated. In tight numeric loops (billions of calls) dispatch can matter, which is why performance-critical code sometimes uses generics or code generation instead; in request-handling code it never does.

Experiment 3: patterns as functions

Many patterns shrink to a function in languages with first-class functions:

Python
def with_retry(fetch, attempts=3):
    def wrapped(day):
        for i in range(attempts):
            try: return fetch(day)
            except ConnectionError:
                if i == attempts - 1: raise
    return wrapped
pricing = {"flat": lambda q: 120 * q, "bulk": lambda q: 108 * q if q >= 10 else 120 * q}   # Strategy as a dict

The functional forms are shorter; the class forms carry names, state and documentation better when behaviour grows. Choose by the size of the behaviour, not by fashion.

Try it yourself

  1. Add a CircuitBreaker decorator that stops calling the supplier after 5 consecutive failures for 10 s, and place it in the stack. Where does it belong relative to Retry?
  2. Implement the order lifecycle with the State pattern and then as a transition table; compare how each handles an illegal transition.
  3. Wrap a real HTTP client (requests.Session or Go's http.Client) with logging and retry decorators via its extension point (HTTPAdapter, RoundTripper).
  4. Find three patterns in a framework you use daily and name the problem each solves there.

Revision sheet: design patterns

Key ideas

  • Patterns are named solutions with forces and trade-offs; use when the problem is present.
  • Creational: Factory Method, Abstract Factory, Builder, Prototype; Singleton mostly replaced by dependency injection.
  • Structural: Adapter, Decorator, Facade, Composite, Proxy, Bridge, Flyweight.
  • Behavioural: Strategy, Observer, Command, State, Template Method, Chain of Responsibility, Iterator, Visitor, Mediator, Memento.
  • Composition over inheritance: most structural/behavioural patterns compose objects behind interfaces.
  • Functional equivalents: higher-order functions (Strategy, Decorator, Command), closures, pattern matching (Visitor), iterators/generators.
  • Architectural cousins: middleware chains, plug-ins, pub/sub, repositories, unit of work.

Numbers to remember

  • Lab: Retry lifted success 70% → 98%; Cache cut supplier calls 1,370 → 12.
  • Lab: ≈50 ns per Python decorator layer; Go interface dispatch ≈ a direct call.

Pitfalls

  • Pattern-first design ("let's use a factory here").
  • Singletons hiding global state and blocking tests.
  • Deep inheritance hierarchies via Template Method.
  • Decorator stacks in an order nobody documented.
  • Visitor and Abstract Factory where a switch or a dict would do.

Glossary

  • Forces: the competing concerns a pattern balances.
  • Composite: treat a tree of objects like one object.
  • Proxy: stand-in controlling access (lazy, remote, protected).
  • Command: an operation as an object (queue, undo, log).
  • Chain of responsibility: pass a request along handlers until one handles it.