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.
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:
src = Metrics(Cache(Retry(FlakyProvider())))
1,000 menu requests spread over 7 days:
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:
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.
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) Storagechoosing 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()));
};
}
// Go: constructor functions (NewX) are the idiom; return concrete types, accept interfaces
func NewBlobStore(cfg StorageConfig) (BlobStore, error) {
switch cfg.Kind {
case "s3":
return newS3Store(cfg.Bucket)
case "local":
return &fileStore{dir: cfg.Dir}, nil
default:
return nil, fmt.Errorf("unknown storage kind %q", cfg.Kind)
}
}
// Rust: associated constructor functions; fallible creation returns Result
impl Email {
pub fn parse(raw: &str) -> Result<Self, EmailError> {
let v = raw.trim().to_lowercase();
if v.contains('@') && v.len() <= 254 { Ok(Self(v)) } else { Err(EmailError::Invalid) }
}
}
// Conventions: new() for infallible, try_new()/parse()/from_*() for others; Default trait for defaults.
# Python: classmethods as alternative constructors
@dataclass(frozen=True)
class Money:
minor: int
currency: str
@classmethod
def of(cls, amount: str, currency: str) -> "Money":
return cls(int(Decimal(amount) * 100), currency.upper())
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: 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();
// Kotlin: named and default arguments make most builders unnecessary
data class HttpRequestSpec(
val uri: URI,
val method: String = "GET",
val timeout: Duration = 5.seconds,
val headers: Map<String, String> = emptyMap(),
) { init { require(timeout > Duration.ZERO) } }
val spec = HttpRequestSpec(URI("https://api.example.com/orders"), method = "POST", timeout = 2.seconds)
// Go: functional options pattern — the idiomatic builder alternative
type Server struct { addr string; readTimeout time.Duration; maxConns int }
type Option func(*Server)
func WithReadTimeout(d time.Duration) Option { return func(s *Server) { s.readTimeout = d } }
func WithMaxConns(n int) Option { return func(s *Server) { s.maxConns = n } }
func NewServer(addr string, opts ...Option) *Server {
s := &Server{addr: addr, readTimeout: 5 * time.Second, maxConns: 1000} // defaults
for _, opt := range opts { opt(s) }
return s
}
srv := NewServer(":8080", WithReadTimeout(2*time.Second))
// Rust: builders are common (e.g. reqwest::ClientBuilder); typestate builders can make
// required fields a compile-time requirement
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(2))
.user_agent("orders/1.0")
.build()?;
# Python: keyword arguments with defaults (dataclasses) cover most builder needs
@dataclass(frozen=True)
class RequestSpec:
uri: str
method: str = "GET"
timeout_s: float = 5.0
headers: Mapping[str, str] = field(default_factory=dict)
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
Cloneableis widely considered broken (shallow copy, no constructor, checked exception); prefer copy constructors orwith-style methods on records. - Kotlin
data class copy(), C#recordwithexpressions, Rust#[derive(Clone)], Pythoncopy.deepcopy/dataclasses.replace, JavaScriptstructuredCloneor object spread. - JavaScript's object model is literally prototype-based (objects delegate to prototype objects).
// 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
}
}
// Go: adapting a function to an interface (http.HandlerFunc is the canonical example)
type HandlerFunc func(http.ResponseWriter, *http.Request)
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { f(w, r) }
// Any function with the right signature becomes an http.Handler.
// Rust: implement your trait for a foreign type via a newtype wrapper (orphan rule)
pub struct AcmeRates(acme_fx::Client);
impl ExchangeRates for AcmeRates {
fn rate(&self, from: Currency, to: Currency, on: NaiveDate) -> Result<Decimal, RatesError> {
let q = self.0.quote(&format!("{from}{to}"), on).map_err(RatesError::vendor)?;
q.mid.parse().map_err(RatesError::parse)
}
}
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.
// 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);
// Go: decorators as wrapper types; http middleware is the most common form (see below)
type instrumentedStore struct {
inner Store
hist metric.Float64Histogram
}
func (s instrumentedStore) Get(ctx context.Context, id string) (Item, error) {
start := time.Now()
item, err := s.inner.Get(ctx, id)
s.hist.Record(ctx, time.Since(start).Seconds(), metric.WithAttributes(attribute.Bool("error", err != nil)))
return item, err
}
# Python: function decorators are the language-level form
import functools, time
def timed(metric):
def wrap(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
metric.observe(time.perf_counter() - start)
return inner
return wrap
@timed(QUOTE_LATENCY)
def quote(cart): ...
// TypeScript: higher-order function decorating any async function with retries
const withRetry = <A extends unknown[], R>(fn: (...a: A) => Promise<R>, attempts = 3) =>
async (...args: A): Promise<R> => {
for (let i = 1; ; i++) {
try { return await fn(...args); }
catch (e) { if (i >= attempts) throw e; await sleep(2 ** i * 50 * Math.random()); }
}
};
const getQuote = withRetry(pricingClient.quote.bind(pricingClient));
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).
# 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),
}
}
}
// Java: classic composite with a common interface (sealed for exhaustiveness)
public sealed interface FileNode permits File, Directory {
long size();
}
public record File(String name, long bytes) implements FileNode {
public long size() { return bytes; }
}
public record Directory(String name, List<FileNode> children) implements FileNode {
public long size() { return children.stream().mapToLong(FileNode::size).sum(); }
}
// TypeScript: UI trees are composites (React components render children uniformly)
type Node = { kind: "text"; value: string } | { kind: "group"; children: Node[] };
const render = (n: Node): string =>
n.kind === "text" ? n.value : n.children.map(render).join("");
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.Proxydynamic proxies; JavaScriptProxyobjects. - Network proxies, service-mesh sidecars and API gateways at the infrastructure scale.
// 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());
// Go: function types as strategies
type Backoff func(attempt int) time.Duration
func Constant(d time.Duration) Backoff { return func(int) time.Duration { return d } }
func Exponential(base, max time.Duration) Backoff {
return func(a int) time.Duration { return min(max, base<<a) }
}
type Retrier struct{ backoff Backoff; attempts int }
// Rust: generic strategies (static dispatch, zero cost) or closures
pub fn sort_orders<F>(orders: &mut [Order], key: F) where F: Fn(&Order) -> i64 {
orders.sort_by_key(key);
}
sort_orders(&mut orders, |o| -o.total.minor()); // strategy as a closure
-- Haskell: higher-order functions make Strategy disappear into ordinary arguments
sortOrdersBy :: (Order -> Order -> Ordering) -> [Order] -> [Order]
sortOrdersBy = sortBy
newestFirst = sortOrdersBy (comparing (Down . createdAt))
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.
// 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 */ }
}
// TypeScript: a typed event emitter
type Events = { "order.placed": { orderId: string; total: number } };
class Emitter<E extends Record<string, unknown>> {
private handlers: { [K in keyof E]?: Array<(e: E[K]) => void> } = {};
on<K extends keyof E>(k: K, h: (e: E[K]) => void) { (this.handlers[k] ??= []).push(h); return () => this.off(k, h); }
off<K extends keyof E>(k: K, h: (e: E[K]) => void) { this.handlers[k] = this.handlers[k]?.filter((x) => x !== h); }
emit<K extends keyof E>(k: K, e: E[K]) { this.handlers[k]?.forEach((h) => h(e)); }
}
// Rust: channels decouple publisher and subscribers (tokio broadcast)
let (tx, _) = tokio::sync::broadcast::channel::<OrderPlaced>(1024);
let mut loyalty_rx = tx.subscribe();
tokio::spawn(async move { while let Ok(e) = loyalty_rx.recv().await { award_points(e).await; } });
tx.send(OrderPlaced { order_id, total })?;
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.
// 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.
// Java 25: sealed state hierarchy; transitions are methods returning the next state
public sealed interface OrderState {
record Created() implements OrderState {}
record Paid(PaymentId payment) implements OrderState {}
record Shipped(String tracking) implements OrderState {}
record Cancelled(String reason) implements OrderState {}
}
public OrderState apply(OrderState s, OrderCommand c) {
return switch (s) {
case OrderState.Created cr when c instanceof Pay p -> new OrderState.Paid(p.paymentId());
case OrderState.Created cr when c instanceof Cancel x -> new OrderState.Cancelled(x.reason());
case OrderState.Paid pd when c instanceof Ship sh -> new OrderState.Shipped(sh.tracking());
default -> throw new IllegalTransition(s, c);
};
}
# Python: classic State pattern — behaviour delegated to state objects
class OrderState:
def pay(self, order, payment_id): raise IllegalTransition(self, "pay")
def ship(self, order, tracking): raise IllegalTransition(self, "ship")
class Created(OrderState):
def pay(self, order, payment_id):
order.payment_id = payment_id
order.state = Paid()
class Paid(OrderState):
def ship(self, order, tracking):
order.tracking = tracking
order.state = Shipped()
class Shipped(OrderState): ...
class Order:
def __init__(self): self.state = Created()
def pay(self, pid): self.state.pay(self, pid)
def ship(self, t): self.state.ship(self, t)
/* C: table-driven state machine — common in embedded and protocol code */
typedef enum { CREATED, PAID, SHIPPED, CANCELLED, N_STATES } state;
typedef enum { EV_PAY, EV_SHIP, EV_CANCEL, N_EVENTS } event;
static const state transitions[N_STATES][N_EVENTS] = {
/* PAY SHIP CANCEL */
[CREATED] = { PAID, -1, CANCELLED },
[PAID] = { -1, SHIPPED, -1 },
[SHIPPED] = { -1, -1, -1 },
};
int step(state *s, event e) {
int next = transitions[*s][e];
if (next < 0) return -1; /* illegal transition */
*s = (state)next;
return 0;
}
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.
// 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.
// 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: 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.
// 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'sDepends. - 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()))
}
// Spring: constructor injection; the container wires beans by type
@Service
public class PlaceOrderHandler {
private final OrderRepository orders;
private final PaymentGateway payments;
private final Clock clock;
public PlaceOrderHandler(OrderRepository orders, PaymentGateway payments, Clock clock) { // no @Autowired needed
this.orders = orders; this.payments = payments; this.clock = clock;
}
}
@Configuration
class TimeConfig { @Bean Clock clock() { return Clock.systemUTC(); } }
# FastAPI: dependency injection via Depends; overridable in tests
from fastapi import Depends, FastAPI
def get_db():
with SessionLocal() as session:
yield session
def get_orders(db = Depends(get_db)) -> OrderRepository:
return SqlOrderRepository(db)
app = FastAPI()
@app.post("/orders")
def place_order(cmd: PlaceOrderIn, orders: OrderRepository = Depends(get_orders)):
return PlaceOrder(orders).handle(cmd)
# tests: app.dependency_overrides[get_orders] = lambda: InMemoryOrders()
// Rust (axum): shared state injected into handlers; trait objects or generics for seams
#[derive(Clone)]
struct AppState { orders: Arc<dyn OrderRepository>, clock: Arc<dyn Clock> }
async fn place_order(State(s): State<AppState>, Json(cmd): Json<PlaceOrderIn>) -> Result<Json<OrderOut>, ApiError> {
let id = ordering::place(&*s.orders, &*s.clock, cmd.into()).await?;
Ok(Json(OrderOut { id }))
}
// main: Router::new().route("/orders", post(place_order)).with_state(AppState { ... })
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).
// 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))
// Express / Koa-style: (req, res, next) or async (ctx, next)
app.use(async (ctx, next) => { // Koa: timing middleware
const start = performance.now();
await next(); // run downstream middleware and handler
ctx.set("Server-Timing", `app;dur=${(performance.now() - start).toFixed(1)}`);
});
// Rust tower: layers wrap services; axum applies them to routers
let app = Router::new()
.route("/orders", post(place_order))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::new(Duration::from_secs(2)))
.layer(CompressionLayer::new()),
);
# Python ASGI (Starlette/FastAPI) middleware
@app.middleware("http")
async def add_request_id(request, call_next):
rid = request.headers.get("x-request-id") or str(uuid4())
response = await call_next(request) # inner layers
response.headers["x-request-id"] = rid
return response
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));
// Rust iterators: zero-cost lazy pipelines compiled into tight loops
let revenue_by_day: BTreeMap<NaiveDate, i64> = orders.iter()
.filter(|o| o.status == Status::Paid)
.map(|o| (o.placed_at.date_naive(), o.total.minor()))
.fold(BTreeMap::new(), |mut acc, (day, amt)| { *acc.entry(day).or_insert(0) += amt; acc });
# Python generators: streaming pipeline with constant memory over a huge file
def read_lines(path):
with open(path) as f:
yield from f
def parse(lines):
for line in lines:
yield json.loads(line)
def paid(events):
return (e for e in events if e["type"] == "payment.succeeded")
total = sum(e["amount"] for e in paid(parse(read_lines("events.jsonl"))))
// Go: pipeline of goroutines connected by channels (concurrent stages)
func generate(ctx context.Context, paths []string) <-chan string { /* emit paths */ }
func resize(ctx context.Context, in <-chan string) <-chan Image { /* one stage, N workers */ }
func upload(ctx context.Context, in <-chan Image) <-chan Result { /* ... */ }
for r := range upload(ctx, resize(ctx, generate(ctx, paths))) { report(r) }
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 |
-- 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: 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
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:
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
- Add a
CircuitBreakerdecorator that stops calling the supplier after 5 consecutive failures for 10 s, and place it in the stack. Where does it belong relative toRetry? - Implement the order lifecycle with the State pattern and then as a transition table; compare how each handles an illegal transition.
- Wrap a real HTTP client (
requests.Sessionor Go'shttp.Client) with logging and retry decorators via its extension point (HTTPAdapter,RoundTripper). - 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
switchor 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.