Essential Design Patterns
Ten patterns every backend developer is asked about, with runnable Java code: Factory Method, Singleton, Builder, Strategy, Observer, Proxy, Adapter, Decorator, plus the microservices patterns Circuit Breaker and Saga — when to use each, look-alikes, and where Spring uses them.
Introduction to Design Patterns
What design patterns are, the creational / structural / behavioral categories, distributed-systems patterns, and the ten patterns covered in this topic.
Factory Method Pattern
Creating objects without exposing creation logic — the notification-factory example, Product / Creator roles, simple factory vs Factory Method vs Abstract Factory, and factories in Spring.
Singleton Pattern
Guaranteeing one instance — the enum singleton, eager and lazy initialization, double-checked locking with volatile, the holder idiom, breaking singletons with reflection and serialization, and Spring singleton scope.
Builder Pattern
Constructing complex objects step by step — the telescoping-constructor problem, a fluent immutable User builder, validation in build(), Lombok @Builder, records, and builders in the JDK and Spring.
Strategy Pattern
Interchangeable algorithms chosen at runtime — the payment-strategy example, Context and Strategy roles, replacing if-else chains, lambdas as strategies, and selecting strategies with Spring injection.
Observer Pattern
One-to-many notification — the YouTube channel example, Subject and Observer roles, push vs pull, thread safety, Spring application events, and how Observer relates to pub/sub messaging.
Proxy Pattern
Controlling access to another object — the bank-account protection proxy, kinds of proxies (protection, virtual, remote, caching, logging), dynamic proxies, and how Spring AOP, @Transactional and Hibernate lazy loading use proxies.
Adapter Pattern
Making incompatible interfaces work together — wrapping a legacy payment gateway, object vs class adapters, adapters in the JDK and Spring MVC, and the hexagonal-architecture view.
Decorator Pattern
Adding behaviour dynamically by wrapping — the coffee example, IS-A plus HAS-A, avoiding subclass explosion, Java I/O streams as decorators, and decorators in Spring.
Circuit Breaker Pattern
Stopping calls to an unhealthy dependency — the CLOSED / OPEN / HALF_OPEN state machine, a simplified implementation, its limitations, Resilience4j in Spring Boot, fallbacks, and related resilience patterns.
Saga Pattern
Business consistency across microservices — local transactions and compensating transactions, an order–payment–inventory saga, choreography vs orchestration, idempotency, and why compensation is not rollback.
Design Patterns Cheat Sheet
Every pattern in one place — purpose, memory hook, the question it answers, one-line interview definitions, look-alike comparisons and practice problems.