Lab 08: Design Patterns

Objective

Implement four essential GoF design patterns in idiomatic Java 21: Builder (fluent order construction), Factory Method (pluggable shippers), Observer (event bus), and Strategy (interchangeable pricing algorithms).

Background

Design patterns are reusable solutions to recurring software design problems. They're not code templates but concepts — the same pattern may look different depending on the language. In Java 21, records, lambdas, and sealed interfaces make many patterns significantly more concise than the classic Gang-of-Four implementations.

Time

30 minutes

Prerequisites

  • Lab 07 (Java 21 Features)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Builder, Factory, Observer, Strategy, Command, Singleton, Decorator, Capstone

💡 Strategy pattern with lambdas: In Java 21, functional interface strategies are just lambdas — no need for concrete classes unless you need state. The PricingStrategy interface with apply and label methods is a named functional interface that's also composable: you can chain strategies (apply bulk discount, then apply loyalty discount) using the same pattern as Function.andThen.

📸 Verified Output:


Summary

Pattern
Intent
Java 21 idiom

Builder

Step-by-step complex object construction

Inner Builder class with fluent setters

Factory Method

Decouple creation from usage

Map<String, Supplier<T>> registry

Observer

Notify multiple listeners of events

EventBus<T> with Map<String, List<Listener>>

Strategy

Swap algorithms at runtime

Functional interface + lambda

Further Reading

Last updated