GoF Design Patterns: The 23 Classic Patterns in Java 21 & UML
The definitive reference for all 23 Gang of Four software design patterns. Explore Creational, Structural, and Behavioral patterns with clean UML diagrams, production Java 21 implementations, and architectural trade-off comparisons.
1. The Three GoF Pattern Classifications
In 1994, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides published Design Patterns: Elements of Reusable Object-Oriented Software. They grouped 23 patterns into three distinct scopes:
Creational (5 Patterns)
Abstract the instantiation process, making systems independent of how objects are created, composed, and represented.
Singleton, Factory Method, Abstract Factory, Builder, PrototypeStructural (7 Patterns)
Concern how classes and objects are composed to form larger structures while keeping relationships flexible and decoupled.
Adapter, Bridge, Composite, Decorator, Facade, Flyweight, ProxyBehavioral (11 Patterns)
Characterize the complex control flow, communication, and assignment of responsibilities between cooperating objects.
Strategy, Observer, State, Command, Chain of Responsibility, Mediator, Iterator, Memento, Visitor, Template Method, Interpreter2. Architectural Blueprint: Strategy Pattern UML & Execution Flow
The Strategy pattern enables algorithm family definition, encapsulating each algorithm into a separate class and making them interchangeable at runtime without mutating context clients:
+---------------------------------------------------------------------------------+
| STRATEGY PATTERN CLASS TOPOLOGY |
+---------------------------------------------------------------------------------+
+------------------------+
| OrderProcessor | (Context)
+------------------------+
| - strategy: PayStrategy|
+------------------------+
| + setStrategy(...) |
| + processOrder(...) |
+------------------------+
|
| <>------ (has-a composition)
v
+------------------------+
| <<interface>> |
| PaymentStrategy | (Strategy)
+------------------------+
| + pay(amount: BigDecimal)
+------------------------+
^ ^ ^
| | | (implements realization)
+---------+ +-----+-----+ +---------+
| | | |
+-------------+ +-------------+ +-------------+ +-------------+
|CreditCardPay| | PayPalPay | | ApplePay | | CryptoPay |
+-------------+ +-------------+ +-------------+ +-------------+3. Modern Java 21 Implementation: Sealed Strategy & Pattern Matching
Leveraging Java 21 sealed interfaces and record patterns ensures compile-time exhaustive strategy evaluation:
| 1 | // ========================================================================= |
| 2 | // UML CLASS MODEL: Strategy Pattern (Behavioral Family) |
| 3 | // <<interface>> Strategy Contract with Exhaustive Sealed Variants |
| 4 | // ========================================================================= |
| 5 | public sealed interface PaymentStrategy |
| 6 | permits CreditCardStrategy, PayPalStrategy, CryptoStrategy { |
| 7 | PaymentReceipt execute(BigDecimal amount); |
| 8 | } |
| 9 | |
| 10 | // <<class>> ConcreteStrategyA |
| 11 | public record CreditCardStrategy(String cardNumber, String cvv) implements PaymentStrategy { |
| 12 | @Override |
| 13 | public PaymentReceipt execute(BigDecimal amount) { |
| 14 | // Authorize with Stripe / Visa Gateway |
| 15 | return new PaymentReceipt("TX-CC-" + UUID.randomUUID(), amount, Status.SUCCESS); |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | // <<class>> ConcreteStrategyB |
| 20 | public record PayPalStrategy(String email) implements PaymentStrategy { |
| 21 | @Override |
| 22 | public PaymentReceipt execute(BigDecimal amount) { |
| 23 | // Authorize via OAuth2 PayPal Token |
| 24 | return new PaymentReceipt("TX-PP-" + UUID.randomUUID(), amount, Status.SUCCESS); |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | // <<class>> ConcreteStrategyC |
| 29 | public record CryptoStrategy(String walletAddress) implements PaymentStrategy { |
| 30 | @Override |
| 31 | public PaymentReceipt execute(BigDecimal amount) { |
| 32 | // Broadcast tx to RPC node |
| 33 | return new PaymentReceipt("TX-BTC-" + UUID.randomUUID(), amount, Status.SUCCESS); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // <<class>> Context: Algorithm Dispatcher & Pattern Matching Executor |
| 38 | public class CheckoutService { |
| 39 | public PaymentReceipt checkout(BigDecimal amount, PaymentStrategy strategy) { |
| 40 | // Compile-time exhaustive pattern matching evaluation |
| 41 | return switch (strategy) { |
| 42 | case CreditCardStrategy cc -> cc.execute(amount); |
| 43 | case PayPalStrategy pp -> pp.execute(amount); |
| 44 | case CryptoStrategy crypto -> crypto.execute(amount); |
| 45 | }; |
| 46 | } |
| 47 | } |
4. Key GoF Pattern Comparison Matrix
Interviewers frequently test subtle distinctions between structurally similar patterns:
| Comparison | Structural Similarity | Fundamental Difference in Intent | Primary Trade-off |
|---|---|---|---|
| Strategy vs. State | Context class delegates behavior to an interface. | Strategy is chosen externally by client. State switches dynamically and automatically based on state machine lifecycle. | State creates higher coupling between concrete state classes; Strategy requires client to know algorithm choices. |
| Decorator vs. Proxy | Both wrap an object implementing the same interface. | Decorator dynamically adds behavior / features. Proxy controls and manages access (lazy loading, auth, caching). | Decorator can result in deeply nested wrapper chains; Proxy can hide expensive remote network calls. |
| Factory Method vs. Abstract Factory | Both abstract concrete object creation. | Factory Method uses inheritance and creates a single product. Abstract Factory uses composition to create families of related products. | Abstract Factory requires adding new factory methods across all concrete factories when a new product type is introduced. |
| Adapter vs. Facade | Both provide a wrapper around existing classes. | Adapter converts an incompatible interface to match a specific expected contract. Facade simplifies a complex subsystem interface. | Adapter preserves existing interfaces; Facade defines a brand-new higher-level interface. |
Frequently Asked Questions (GoF Design Patterns)
What is the key difference between Strategy Pattern and State Pattern?
While both patterns share nearly identical UML class structures (a Context delegating to an Interface), their intent is fundamentally different. In the Strategy Pattern, the client explicitly chooses which interchangeable algorithm or strategy to inject into the Context. In the State Pattern, the Context changes its internal state transitions dynamically and automatically changes its behavior based on internal lifecycle triggers.
How does Java 21 modernize the classic GoF patterns?
Modern Java 21 drastically reduces GoF boilerplate: Sealed Interfaces and Pattern Matching for switch replace complex Visitor patterns; Records replace verbose Data Transfer and Prototype classes; Lambdas and method references eliminate single-method Strategy and Command classes; and Virtual Threads replace complex worker-thread pooling patterns.
What is the difference between Decorator, Proxy, and Adapter patterns?
Adapter changes an incompatible interface to match what a client expects. Decorator keeps the same interface but enhances it with additional responsibilities dynamically. Proxy keeps the same interface but controls and manages access to the underlying object (e.g., lazy loading, security check, or caching).