Lab 04: Design Patterns Advanced

Objective

Implement four advanced GoF patterns using Java 21 idioms: Decorator (composable price transforms), Chain of Responsibility (validation pipeline via functional composition), Visitor (type-safe product analytics), and Template Method (pluggable report formats).

Background

Advanced patterns differ from basic ones in composability — each adds a new layer around existing behaviour without modifying it (Open/Closed Principle). Java 21's sealed interfaces and functional composition make these patterns far more concise than classic implementations, while sealed types make Visitor exhaustive and compiler-verified.

Time

30 minutes

Prerequisites

  • Practitioner Lab 08 (Design Patterns), Lab 07 (Java 21 Features)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Decorator pipeline, Chain of Responsibility, Visitor with sealed, Template Method, Capstone

💡 Decorator vs inheritance: Decorator adds behaviour at runtime by wrapping objects, not at compile-time via subclassing. withTax(withDiscount(base(), 0.10), 0.08) creates a three-layer stack where each layer sees the transformed price from the layer below. Adding a new transform (e.g., loyalty cashback) requires zero changes to existing classes — just a new wrapper function.

📸 Verified Output:


Summary

Pattern
Java 21 idiom
Benefit

Decorator

Wrapper returning same interface

Composable behaviour layers

Chain of Responsibility

default andThen composition

Ordered validation pipeline

Visitor

Sealed accept(visitor) + switch

Type-safe, exhaustive dispatch

Template Method

abstract methods in base class

Fixed algorithm, pluggable steps

Further Reading

Last updated