Example demos

Runnable companions to the book.

Every pattern chapter has a demo behind it. Each demo is a self-contained, standalone-buildable Maven module with a JUnit 5 and AssertJ test suite, Mockito where a collaborator needs mocking, and no containers. Read the matching chapter for context, then build the demo from its directory with the same local JDK the prerequisites chapter installs.

Runnable examples

Each example makes a single pattern concrete and runnable with one command. Every card links to the demo's page on this site (a rendering of the README with cross-references), and each page links to the source on GitHub. Each demo also stands alone, so you can build it without reading the book first if you'd rather poke at it directly.

Chapter 3 · SOLID I

SRP, OCP, LSP in a billing engine

A freight-invoice calculator split into calculation, formatting, and persistence (SRP); an InvoiceRule abstraction that takes new rules without edits (OCP); and a discount rule that stays substitutable, with a counter-example that does not (LSP).

Read page →
Chapter 4 · SOLID II

ISP, DIP, and DI without a framework

A fat notification gateway split into MessageSender, TemplateRenderer, and DeliveryStatusProvider (ISP); a policy that depends on those abstractions, not a concrete gateway (DIP); and constructor injection hand-wired in plain Java, with Mockito standing in for a collaborator.

Read page →
Chapter 5 · Resource management

try-with-resources and Execute-Around

Shipping resources that implement AutoCloseable and release deterministically through try-with-resources, plus an Execute-Around method that owns setup and teardown around a caller's lambda. Tests prove close() runs on the normal path and when an exception unwinds the block.

Read page →
Chapter 6 · Encapsulation

Interfaces, static factories, records

A shipping gateway behind a public interface reached through a static factory, with a package-private implementation; immutable value types as records; and a type that defensively copies a collection it holds. Tests prove callers cannot mutate internal state.

Read page →
Chapter 7 · Testing

JUnit 5, Mockito, and AssertJ

A shipping component under test demonstrating the book's testing stack: the JUnit 5 lifecycle, parameterized tests, exception assertions, Mockito mocks and spies with verify and ArgumentCaptor, and AssertJ fluent assertions, all aimed at behavior rather than implementation.

Read page →
Chapter 8 · Strategy

Shipping-rate estimation

A checkout picks a carrier rate rule at runtime. The same pattern shown three idiomatic Java ways: a classic interface with concrete classes, a functional interface with lambdas, and an enum whose constants carry their own algorithm.

Read page →
Chapter 9 · Template Method

A fixed order-processing skeleton

An order-processing pipeline whose sequence is fixed and final, with the varying steps supplied two ways: by overriding an abstract class per channel, and by handing the pipeline lambdas. Tests prove both forms run the same steps in the same order and produce identical results.

Read page →
Chapter 10 · State and FSM

The shipment lifecycle as a state machine

A shipment lifecycle modeled three ways: an enum with a transition table, a sealed interface with an exhaustive pattern-matching switch, and a probabilistic machine driven by an injected RandomGenerator. Tests prove illegal transitions are refused and the two deterministic machines agree.

Read page →
Chapter 11 · Command

A warehouse operations desk

Warehouse operations captured as command objects with execute and undo: immutable records whose undo is an arithmetic inverse, mutable commands that snapshot prior state at execute time, an undo-redo history on two deques, and a FIFO command queue.

Read page →
Chapter 12 · Factories

A regional shipping desk

Abstract Factory builds a matching label formatter, rate table, and customs form per region behind one interface; static factory methods backed by a Supplier registry resolve the toolkit; a Factory Method with a hook picks the right shipment inspector. Tests prove each factory returns a consistent family.

Read page →
Chapter 13 · Builder and Prototype

Assembling a complex shipment

A Shipment with many optional parts assembled through a static nested Builder that validates every invariant once at build(), a CustomsDeclaration record with wither copies, and a PackagingTemplate prototype cloned into independent copies. Tests prove invalid combinations are rejected and copies are independent.

Read page →
Chapter 14 · Singleton and DI

Singleton and the DI alternative

A carrier rate table as an enum singleton and as an initialization-on-demand holder, a job that reaches a global instance as a hidden dependency, and the dependency-injected alternative that takes the same collaborator through its constructor. Tests show why injection is testable where the global is not.

Read page →
Chapter 15 · Adapter, Facade, Bridge

Composing a shipping subsystem

An Adapter wrapping a foreign courier SDK to the app's CarrierGateway, a Facade presenting one surface over rating, labeling, customs, and tracking, and a Bridge letting notification kinds and delivery channels vary independently. Tests verify the translation, the orchestration order, and the N+M (not N×M) combination.

Read page →
Chapter 16 · Decorator and Proxy

Wrapping a rate quoter

Logging, caching, and surcharge decorators stacked over a RateQuoter (named classes and functional equivalents), a hand-written lazy proxy that defers construction, and a java.lang.reflect.Proxy that gates access by clearance. Tests prove stacking order matters and the dynamic proxy intercepts every call.

Read page →
Chapter 17 · Composite, Flyweight, Null Object

A shipment container tree

A sealed ShipmentNode tree where a parcel and a box answer the same interface, a FlyweightPool interning shared PackagingSpec instances, and a null-object alert handler that removes a null check, with Optional shown as the modern alternative at the boundary. Tests prove aggregation, shared identity, and the safe no-op.

Read page →
Chapter 18 · Observer and Mediator

Tracking and dispatch

A ShipmentTracker subject notifies listeners (named and lambda) on a status change, with subscriptions closed via try-with-resources; a DispatchCoordinator mediates between warehouse, carrier, and customer stations that never call each other directly. Tests verify notification, unsubscription, and decoupled routing.

Read page →
Chapter 19 · Chain of Responsibility and Iterator

Approvals and manifests

A shipment-approval chain (object chain and a functional composition over Optional) that stops at the first handler to take the request, and a ShipmentManifest that implements Iterable with a hand-written iterator plus a stream built on its spliterator. Tests verify routing, the fallback, and traversal order.

Read page →
Chapter 20 · Visitor, Memento, Interpreter

Operations, snapshots, a tiny grammar

Visitor as a sealed ManifestEntry with operations expressed as exhaustive pattern-matching switches (no accept() on the nodes), a ManifestDraft memento whose package-private snapshot record hides its internals, and a small SurchargeExpr grammar that evaluates itself by record-pattern switch. Tests cover every operation, restore, and nested expressions.

Read page →
Chapter 21 · Records, sealed, pattern matching

Data-oriented programming

Sealed ParcelKind, ShippingEvent, and RateRule hierarchies of records, with operations kept as external exhaustive switches (type patterns, guarded when, and record deconstruction nested several levels). Tests verify every switch handles every variant and compact-constructor validation holds.

Read page →
Chapter 22 · Functional Java

Patterns as everyday functional Java

A nightly shipment-fulfillment batch showing enums carrying behavior (Strategy, Singleton), lambdas and method references as Strategy and Command, a Template Method taking functions, composed UnaryOperator adjustments, stream pipelines with EnumMap grouping, and Optional as an explicit maybe-absent return. Tests assert behavior across all of them.

Read page →
Chapter 23 · Idiom retirement

The modern forms, working

The Java 25 replacements for four classic idioms, as working code: an enum singleton (proven under a 32-thread race) for double-checked locking, a record for a hand-written value class and its defensive copies, a sealed interface plus exhaustive switch for the double-dispatch Visitor, and Optional for the null check.

Read page →
Chapter 24 · Virtual threads

Concurrent carrier fan-out

A rate quote fanned out across carriers on virtual threads with newVirtualThreadPerTaskExecutor, an unbounded fan-out and a Semaphore-bounded one, and a ReentrantLock-guarded cache. Tests prove concurrency with CyclicBarrier rendezvous, and the chapter covers what virtual threads are good for and not.

Read page →
Chapter 25 · Resource and concurrency patterns

Pools, monitors, active objects

A bounded CarrierConnectionPool with a blocking, timed acquire and AutoCloseable leases, a DispatchDock monitor serializing access via ReentrantLock + Condition, a LabelPrintActiveObject decoupling a call from its worker thread, and the ThreadLocal cost. Deterministic concurrency tests, no sleeps.

Read page →
Chapter 26 · Shortcut patterns

Dispatch tables and maps

An EnumMap dispatch over a closed ShipmentEventType (exhaustive, compiler-checked) and an open Map webhook router with runtime registration and a fallback. Tests cover every key and the fallback path. The lightweight alternative when a full Strategy/Command hierarchy is overkill.

Read page →
Chapter 27 · Anti-patterns

Pattern misuse, taken apart

An over-engineered pricing design (a mutable-global singleton registry, a one-implementation interface, a factory of factories, a god object with a leaky abstraction) contrasted with the simple ShipmentPricingService. A parameterized equivalence test proves the simple form behaves identically.

Read page →
Chapter 28 · Quarkus and CDI

Patterns as framework features

A Quarkus (Arc) module showing the same forces answered by the container: @ApplicationScoped + constructor @Inject as Singleton/DI, @Produces as Factory, an @AroundInvoke interceptor as Decorator/Proxy, a CDI event + @Observes as Observer, and @ConfigMapping as externalized Strategy. @QuarkusTest suite runs in-JVM on JDK 25 with no container.

Read page →
Chapter 29 · Seams

Getting inherited code under test

A legacy escalation service that reads the wall clock inline and news its own carrier client, pinned with characterization tests, then opened at three seams: an injected Clock (object seam), an extracted CarrierGateway (interface seam with a Mockito double), and a protected overridable method (subclass-and-override). Tests hit exact boundary cases.

Read page →
Chapter 30 · Dependency-breaking

Making hard-wired code testable

A hard-wired legacy shipment processor made testable with Extract Interface + Parameterize Constructor, Extract and Override Factory Method, Subclass and Override Method, and Adapt Parameter. Tests prove the now-testable behavior with Mockito doubles, ArgumentCaptor, and @TempDir.

Read page →
Chapter 31 · Characterization tests

Pinning behavior before changing it

A gnarly legacy freight-quote calculator with three real boundary quirks, pinned by a characterization suite (values computed by running the legacy code, not from a spec), then refactored Fowler-style to a polymorphic carrier model that keeps every pinned case green.

Read page →
Chapter 32 · Refactor, rewrite, strangler

A strangler-fig migration

A legacy accessorial-fee calculator with undocumented carrier rules, a clean modern reimplementation proven equivalent, and a strangler router behind a stable interface that routes each shipment to old or new by a migration registry, so the cutover is invisible slice by slice.

Read page →
Chapter 33 · Final project

A composed shipping system

One coherent system wiring five patterns: a ShipmentBuilder that resolves a rate Strategy per carrier, a Shipment that is both a State machine and an Observer subject, undoable Commands with a history, and status listeners. 39 tests prove the composition, including a Mockito InOrder integration test.

Read page →
Chapter 34 · Working with AI/LLM tools

A verification gate for AI output

A return-eligibility Strategy with two drafts: a correct one and a plausible-but-wrong one (an off-by-one on the day-30 boundary). The gate, a parameterized behavior-test suite, accepts the correct draft and rejects the wrong one, turning a silent misclassification into a caught $40 overpayment.

Read page →

Building every demo

Clone the repo and build every example in one pass with the pinned local toolchain (JDK 25 and Maven; see the prerequisites chapter and scripts/check-prereqs.sh).

git clone https://github.com/patterncatalyst/design-patterns-with-java.git
cd design-patterns-with-java
./scripts/build.sh
./scripts/verify.sh

Every example is also standalone-buildable from its own directory with mvn test, without configuring the whole repo.