Chapters

The whole book, in order.

Thirteen parts, read in order the first time through. Each chapter also stands on its own for a reader jumping in to solve one problem. Pick a part, or start at the top.

Part 0 Orientation

The toolchain (JDK 25, Maven, JUnit 5, Mockito, AssertJ), how to read the book, and the codetabs convention that carries Classic Java and Java 25 side by side through every chapter.

  1. Prerequisites and the toolchainThe JDK 25, Maven, JUnit 5, Mockito, and AssertJ toolchain this book builds against, how the Maven example harness works, and why every code sample in this book is a single idiomatic Java 25 block.

Part 1 Recognizing Design

Patterns as decisions under forces, not recipes to apply by reflex, and the shared vocabulary a team (and an AI pairing partner) needs to name what it sees.

  1. Patterns as decisions under forcesWhy a design pattern is a named response to a recurring set of trade-offs rather than a recipe to apply from memory, and the five-step arc this book trains for every pattern that follows.
  2. Naming the patternWhy a pattern's name is a compression of forces a team, a future reader, and an AI pairing partner can all act on, and why a loose name misleads every one of them the same way.

Part 2 Principles (SOLID, Martin)

The five SOLID principles in modern Java terms: SRP/OCP/LSP first, then ISP/DIP and dependency injection without a framework.

  1. SOLID I: SRP / OCP / LSPA freight-billing engine split along three SOLID principles: one reason to change per type under the Single Responsibility Principle, an InvoiceRule abstraction new rules can satisfy without an edit under the Open/Closed Principle, and a discount rule refined without breaking its parent's contract under Liskov Substitution.
  2. SOLID II: ISP / DIP and dependency injection without a frameworkSplitting a fat interface into focused role interfaces, inverting the dependency between a high-level policy and a low-level detail, and wiring the resulting object graph by hand in idiomatic Java with no DI container.

Part 3 The Java Substrate

Records and sealed interfaces, immutability and defensive copying, and proving a design works with JUnit 5 before the patterns chapters begin.

  1. Resource management (Java's RAII)Deterministic cleanup without a destructor: try-with-resources and AutoCloseable as Java's primary answer, and the Execute-Around Method idiom for the cases a resource's open/use/close sequence belongs to a library rather than every call site, taught against a carrier connection, a batch ledger writer, and a pooled tracking-feed handle.
  2. Encapsulation and API designA shipping-tracking gateway built behind a public interface with a package-private implementation reached through a static factory, and a Shipment/Manifest/TrackingHistory value model built from records whose compact constructors defend every collection field with List.copyOf.
  3. Testing with JUnit 5, Mockito, and AssertJThe testing stack every example in this book runs behind the scenes: JUnit 5's lifecycle and parameterized tests, Mockito's mocks and spies, and AssertJ's fluent assertions, taught against a shipment-booking service with one collaborator mocked and two called directly.

Part 4 Selecting and Varying Behavior

Strategy, Template Method with hooks, State and finite-state machines (including probabilistic ones), and Command with undo and command queues.

  1. StrategyThree idiomatic Java 25 ways to select a varying algorithm, taught against a real shipping-rate example: an interface with named classes, the same contract assigned as a lambda, and a closed set of carriers expressed as enum constants.
  2. Template MethodTwo idiomatic Java 25 ways to keep a processing sequence fixed while its steps vary, taught against a shipment order pipeline that validates, prices, and records an order the same three steps every time, with different content per sales channel: an abstract base with a final skeleton and overridden hooks, and the same skeleton written once as a value whose steps arrive as lambdas.
  3. State and finite state machinesA shipment's lifecycle modeled two idiomatic Java 25 ways, an enum-plus-transition-table machine and a sealed-interface state dispatched through an exhaustive pattern-matching switch, plus a probabilistic machine whose weighted transitions are made reproducible by injecting a seeded RandomGenerator.
  4. Command, undo, and command queuesTurning a warehouse desk's operations into Command objects with their own execute and undo, an undo/redo stack built on a Deque, a FIFO command queue for deferred batch processing, and a functional-interface shortcut for a queued action with nothing to undo.

Part 5 Creating Objects Under Control

Factory Method and Abstract Factory, Builder and Prototype (with serialization), and Singleton alongside the dependency-injection alternative and static factory methods.

  1. Factory Method and Abstract FactoryTwo idiomatic Java 25 ways to keep object creation out of client code, taught against a regional shipping desk: an Abstract Factory that hands out a matching label formatter, rate table, and customs form per region, and a Factory Method that lets a shipment's category decide which inspection checklist runs inside a fixed sequence.
  2. Builder and PrototypeA Bloch-style Builder that assembles an international shipment and validates it only once, at build(), a record with wither methods for deriving a changed customs declaration, and a Prototype catalog that clones a named packaging exemplar into an independent copy, taught against a shipping domain.
  3. Singleton and the DI alternativeThe two modern, correct ways to build a Java singleton, the enum form and the initialization-on-demand holder idiom, the older double-checked-locking approach they retire, and the dependency-injection alternative that gives the same reachable capability without the hidden global.

Part 6 Composing and Adapting Structure

Adapter, Facade, and Bridge, Decorator and Proxy, and Composite and Flyweight alongside the Null Object idiom.

  1. Adapter, Facade, BridgeThree structural techniques taught against one GlobalCourier shipping integration: an Adapter that wraps a third-party rate client's awkward shape behind this app's own interface, a Facade that fronts rating, labeling, customs declaration, and tracking with one call, and a Bridge that lets a notification's kind and its delivery channel vary independently.
  2. Decorator and ProxyTwo structural patterns that wrap an object behind its own interface, taught against a shipping-rate quoting pipeline: Decorator stacks layers that each add one responsibility in an order that changes the result, and Proxy stands a single surrogate in front of an expensive or access-controlled subject without adding any new capability.
  3. Composite, Flyweight, Null ObjectThree idiomatic Java ways to keep a recursive shipment tree simple: a sealed ShipmentNode interface that treats one parcel and an entire pallet identically, a FlyweightPool that interns shared PackagingSpec and Country instances across thousands of parcels, and a Null Object that lets a weight-limit check skip every null branch, contrasted with Optional resolved at a construction boundary.

Part 7 Coordinating and Traversing

Observer and Mediator, Chain of Responsibility and Iterator with streams, and Visitor, Memento, and Interpreter.

  1. Observer and MediatorTwo coordination patterns for a many-party system, taught against a shipment tracker and a warehouse dispatch desk: Observer fans a status change out to independently subscribed listeners behind one functional interface, and Mediator centralizes a many-to-many conversation behind a single hub so a warehouse, a carrier, and a notification service never reference each other directly.
  2. Chain of Responsibility and IteratorTwo patterns for coordinating a collection of objects rather than one: Chain of Responsibility routes a request through a sequence of handlers until one of them acts, built as an object chain and as a Stream-driven functional composition, and Iterator provides sequential access to an aggregate without exposing its internal structure, built by hand against a zone-bucketed shipment manifest and then exposed as a Stream with no extra code, through Iterable's default spliterator() method.
  3. Visitor, Memento, and InterpreterThree idiomatic Java patterns for a fixed shipping-manifest hierarchy: Visitor expressed as a sealed interface and an exhaustive pattern-matching switch that adds operations with no accept() method anywhere, Memento as a package-private snapshot record that lets a draft manifest roll back to an earlier state in one call, and Interpreter as a small sealed surcharge-expression grammar whose nesting decides the evaluated result.

Part 8 Idiomatic Java 25 Expressions

Records and sealed interfaces for pattern matching, functional interfaces and method references in place of classic callback hierarchies, and the Builder and static-factory idioms from Effective Java.

  1. Records, sealed interfaces, and pattern matchingA shipping rating engine built from three closed, sealed record hierarchies, ParcelKind, ShippingEvent, and RateRule, operated on by exhaustive pattern-matching switches that use type patterns, a guarded when clause, and record deconstruction patterns nested three levels deep, with no visitor interface and no accept() method anywhere.
  2. Enums, functional interfaces, streams, and Optional as patternsA nightly shipment fulfillment batch, run entirely through everyday Java 25 constructs: an enum carrying its own algorithm, a lambda satisfying the identical contract, a function standing in for a class hierarchy, composed pricing adjustments, a stream pipeline, and Optional as an explicit answer instead of null.
  3. Where Java 25 retires classic idiomsThe through-line pulled together: an enum singleton retiring double-checked locking, a record retiring a hand-written value class and its defensive copying, a sealed interface with an exhaustive switch retiring Visitor and the instanceof chain, and Optional retiring the Null Object, all in modern Java 25 against one shipping domain.

Part 9 Concurrency and Patterns in the Wild

Resource pools and virtual threads, shortcut patterns such as method-reference tables and dispatch maps, and anti-patterns to recognize and avoid.

  1. Virtual threadsWhat a virtual thread is, why fanning a shipment out to a hundred carrier rate APIs stops being expensive, and the concrete cases, CPU-bound work, pooling, pinning, ThreadLocal at scale, where a virtual thread is the wrong tool.
  2. Resource and concurrency patternsThree idiomatic Java 25 shapes for bounding and serializing concurrent access, taught against a regional parcel-dispatch hub: a bounded connection pool with a blocking acquire, a monitor object that serializes a shared manifest, and an active object that decouples a call from the thread that runs it.
  3. Shortcut patterns: dispatch tables and mapsTwo idiomatic Java 25 shortcuts for routing a key to a short handler without a full Strategy or Command hierarchy, taught against a shipping event feed: an EnumMap built from an exhaustive switch expression, and a Map dispatch table that registers a handler at runtime and falls back on an unrecognized key.
  4. Anti-patterns and pattern misuseRecognizing patternitis in a shipping-rate pricing codebase: a singleton surcharge registry holding global mutable state, a factory-of-factories wrapped around an interface with one implementation, a god object that validates, logs, and formats, and a leaky abstraction that exposes its own call order. The simplified rewrite collapses six types into two records and one class that compute the same answer and are testable where the original was not.
  5. Patterns in a real framework: Quarkus and CDIQuarkus's CDI container, Arc, answers the forces the hand-written patterns answer: constructor injection into a managed bean for Singleton and dependency injection, a producer method for Factory, an interceptor binding for Decorator and Proxy, a CDI event for Observer, and typed configuration for Strategy, in a shipping checkout service.

Part 10 Changing Inherited Code (Modernized Feathers)

Seams and the test safety net, the dependency-breaking techniques updated for Java 25, Fowler contrasted and combined with Feathers, and when to refactor versus rewrite.

  1. Seams and the test safety netGetting a hard-wired shipment escalation service and a risk scorer under test before changing them. Characterization tests pin the current behavior, an object seam and an extract-interface seam make the escalation service's clock and gateway substitutable, and a subclass-and-override seam opens the risk scorer with no constructor change.
  2. Dependency-breaking techniques for JavaMichael Feathers' dependency-breaking techniques in modern Java, on a hard-wired LegacyShipmentProcessor: Extract Interface with Parameterize Constructor opens a seam around a concrete mail dependency, Extract and Override Factory Method around an embedded surcharge calculator, Subclass and Override Method around a wall-clock read, and Adapt Parameter shrinks a manifest-file parameter to the two values a caller reads.
  3. Characterization tests; Fowler vs FeathersCharacterization tests lock in the behavior of an inherited freight-quote calculator before anyone understands it. Fowler's Refactoring assumes that safety net exists, Feathers' Working Effectively with Legacy Code builds it, and the two run in sequence on one calculator.
  4. Refactor, rewrite, or strangler figChoosing between an in-place refactor, a wholesale rewrite and the strangler fig, on a legacy accessorial fee calculator with an undocumented renegotiated fuel rate, a weight-based fee waiver and a carrier-specific oversize penalty. A strangler router sends each shipment to the legacy or modern calculator behind one AccessorialFeeCalculator interface, and a shared characterization table proves the two agree before cutover.

Part 11 Putting It Together

A final project that composes several patterns from the book, and a look at working with AI and LLM tools as a pattern-literate collaborator rather than a code vending machine.

  1. Final projectA shipment dispatch center that composes Builder, State, Command, Observer and Strategy into one running system, taught at the seams where the patterns meet.
  2. Working with AI and LLM toolsUsing an LLM as a pattern-literate collaborator: name the forces and the candidate pattern before prompting, recognize patternitis, hallucinated APIs and non-idiomatic Java, and pass every draft through a verification gate of behavior tests plus an idiomatic review. A return-eligibility Strategy pairs a correct draft with a plausible one carrying a single off-by-one, caught by the same boundary table.

Part 12 Appendices

A build and toolchain reference, a JUnit 5 reference, a Mockito mocking reference, an xUnit test-patterns guide, a pattern-to-force quick reference that maps every pattern, principle, and idiom in the book to the forces it answers, and a code-first review of the wider programming-principle vocabulary beyond SOLID.

  1. Build and toolchain referenceReference for building and testing every example: the pinned toolchain, the Maven aggregator and per-module layout, standalone versus whole-repository builds, the scripts/ helpers, both IDEs, and the Quarkus plus JBang track.
  2. JUnit 5 referenceReference for the JUnit 5 annotations, lifecycle, assertions, parameterized and dynamic tests the examples use, and how Maven Surefire runs them.
  3. Mockito referenceReference for Mockito: mock() and @Mock, stubbing with when/thenReturn and doReturn/doThrow, spy(), verify() with times, never and InOrder, argument matchers, ArgumentCaptor, and strict stubbing, on shipping collaborators.
  4. xUnit test patternsGerard Meszaros's xUnit test patterns, the four-phase test, the test-double taxonomy, fixture strategies, and the common test smells, mapped onto JUnit 5, Mockito, and AssertJ.
  5. Pattern-to-force quick referenceEvery GoF pattern, SOLID principle, and Java idiom mapped to the force that justifies it, each linked to the chapter that builds it. Scan it to find the tool for the force in front of you.
  6. Programming principles, reviewed in codeThe principle vocabulary beyond SOLID that every Java engineer is expected to recognize, each shown as a before-and-after shipping-domain snippet with the point where it starts costing more than it returns.