Learning pathsPricingChecking sign-in…
Foundations

Design patterns

Use a pattern to resolve a named source of change.

Explore the design exercises →

A design pattern names a recurring arrangement of responsibilities. First identify the pressure: interchangeable algorithm, lifecycle-dependent legality, fan-out, construction or tree ownership. Then choose the smallest pattern that solves it and show how it protects an invariant.

Learning goals

  • Choose patterns from a named source of change.
  • Understand behavioral contracts and failure costs behind common patterns.
  • Compare a simple conditional/table implementation with a class-based implementation.

What, when, why and how

Strategy

what
Encapsulate interchangeable algorithms behind one input/output contract.
when
Pricing, allocation or scheduling policy varies while mechanism remains stable.
why
Copying conditionals into every caller spreads changes.
how
Inject the policy; validate its result before committing domain state. Keep policy versions when replay/audit depends on historical meaning.

Worked example: An inventory allocation strategy proposes warehouse quantities; the inventory owner still validates conservation and availability.

Common mistake: Calling a strategy does not transfer transaction ownership to it. A policy cannot commit half an order.

State

what
Represent behavior whose legal actions depend on lifecycle stage.
when
A vending machine accepts coins while collecting but not while dispensing.
why
Independent booleans permit impossible combinations and scattered checks.
how
Start with an enum plus explicit transition table. Introduce state objects when behavior is substantial, while one owner controls transitions.

Worked example: ACTIVE hold transitions to CAPTURED or RELEASED once; an unresolved physical action keeps a separate unknown state.

Common mistake: A class per enum value can add ceremony without clarifying any transition or invariant.

Observer / publish-subscribe

what
Register consumers and notify them when an event is published.
when
Optional consumers evolve independently from a producer.
why
Producer knowledge of every handler couples unrelated modules.
how
Define snapshot eligibility, invocation ordering, failure isolation and per-consumer backpressure before implementation. Call user handlers outside registry ownership.

Worked example: An Event Bus snapshots A/B; A unsubscribes B in its callback but B still receives this publication under the declared snapshot contract.

Common mistake: Observer is not durable exactly-once delivery. Queued, processed and externally committed are different acknowledgements.

Factory

what
Centralize creation when valid construction depends on configuration or subtype selection.
when
Objects need validated combinations or provider-specific setup.
why
Duplicated creation logic allows inconsistent validation and ownership.
how
Keep constructors useful for simple values; add a factory when selecting dependencies or assembling a valid aggregate requires coordinated rules.

Worked example: A configured notification adapter factory selects one provider with credentials, deadline policy and result mapping.

Common mistake: A factory should not hide network I/O or return a partially initialized domain owner.

Adapter and Decorator

what
Adapter translates one contract to another; Decorator wraps a contract to add behavior while preserving its meaning.
when
Provider APIs differ, or metrics/redaction must surround existing logic.
why
Leaking provider DTOs or duplicating instrumentation increases coupling.
how
Keep provider acknowledgement translation in an adapter. Use a decorator for bounded metrics/timing that preserves exceptions and outcome semantics.

Worked example: A timed gateway records latency and returns the same UNKNOWN result rather than converting timeout into definite failure.

Common mistake: A retry decorator can violate idempotency and duplicate external effects; wrapping is not automatically transparent.

Composite

what
Treat a tree of objects through a shared traversal/operation interface where the operations make sense.
when
Files and directories form a namespace hierarchy.
why
Separate ad hoc traversal code duplicates cycle/ownership logic.
how
Keep parent ownership, child-name uniqueness and node-specific operations explicit. A directory lists children; file bytes belong to a file. Reject invalid cross-type operations.

Worked example: Recursive deletion traverses the directory tree; moving a directory into its descendant must reject.

Common mistake: A filesystem with hard links is a graph and has different identity/deletion rules from this simple ownership tree.

Command and Repository

what
Command records intent with identity; Repository exposes domain-specific persistence operations.
when
Retries, audit/replay or storage boundaries are required.
why
A naked function call loses command meaning, while generic CRUD hides concurrency requirements.
how
Store command fingerprint/result identity for retry. Expose repository methods such as claimSeatsIfAvailable, not a bag of independent setters. Use a transaction owner for atomic multi-row operations.

Worked example: A stable Ship command key binds reservation and quantities. Matching retries return prior logical effect; changed inputs under that key reject.

Common mistake: Command is not automatically event sourcing, and Repository does not make arbitrary remote effects transactional.

Strategy separates allocation proposal from state ownership

Illustrative Java 21 snippet; the linked exercises contain complete executable references and tests.

Solution.java Java 21
import java.util.List;
interface SeatChoice {
    List<String> choose(List<String> available, int count);
}
final class FirstAvailable implements SeatChoice {
    public List<String> choose(List<String> available, int count) {
        if (count < 1 || count > available.size())
            throw new IllegalArgumentException("count");
        return List.copyOf(available.subList(0, count));
    }
}

This policy returns an immutable proposal and performs no reservation. The inventory owner must revalidate current availability and atomically claim the chosen seats. Calling choose on an old snapshot cannot itself prevent double booking. An adjacent-seat strategy would need row/seat metadata and its own deterministic policy tests.

Worked design exercise

Select patterns for a vending machine without creating unnecessary classes.

  1. List states and legal commands: idle, collecting, dispensing and unresolved outcome.
  2. Use a transition table/enum for state guards first.
  3. Separate change-making algorithm as a strategy only if policies genuinely vary.
  4. Represent a physical vend as a stable command returned to an adapter.
  5. Retain definite outcome evidence; use observers only for optional telemetry.
Compare your reasoning with the worked answer

State clarifies legality, Command/Adapter isolates physical uncertainty and Strategy can isolate real algorithm variation. None requires a hierarchy for every product or coin. The machine remains the owner of escrow, reservations and terminal outcomes.

Engineer to Staff follow-ups

Engineer: How are Strategy and State different?

Strategy selects an algorithm under one contract; State determines which actions/behavior are legal at a lifecycle stage.

Senior: When should Observer be avoided?

When the producer needs a required synchronous result from a specific dependency. A direct typed call often makes that contract clearer.

Staff: Can a pattern ensure durable recovery?

No. Durable recovery additionally needs persisted identity/state, transaction boundaries, retry/replay compatibility and reconciled external outcomes. Patterns organize those responsibilities.

Apply it in design exercises

For each exercise, derive the object owner, schema keys/relationships and transaction boundary before revealing the reference.

Your study notes