DevNotes
Support
Essential Design Patterns · Chapter 12

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.

◷ 5 min read§ 10 sections? 0 interview questions{ } 0 code examples

#Introduction

A one-page revision of all ten patterns in this topic — use it the day before an interview.

#Quick Revision

PatternCategoryPurposeMemory hookThe question it answers
Factory MethodCreationalCreate objects without exposing creation logicCreator → factory method → product"Which object should I create?"
SingletonCreationalOnly one instanceSingleton.getInstance() or EnumSingleton.INSTANCE"How do I guarantee one shared instance?"
BuilderCreationalBuild a complex object step by stepnew User.Builder().name(…).age(…).build()"How do I construct an object with many parameters?"
StrategyBehavioralChoose an algorithm at runtimeContext → Strategy → A / B"Which algorithm or behaviour should I use?"
ObserverBehavioralNotify multiple objectsSubject → observers"Who should be notified when something changes?"
ProxyStructuralControl accessClient → proxy → real object"Should the client be allowed to access the real object?"
AdapterStructuralMake incompatible interfaces workClient → adapter → existing system"How can these incompatible interfaces communicate?"
DecoratorStructuralAdd behaviour dynamicallyDecorator → decorator → real object (coffee + milk + sugar + chocolate)"How can I add optional features without subclass explosion?"
Circuit BreakerMicroservicesPrevent cascading failureCLOSED = call, OPEN = stop, HALF_OPEN = test"Should I keep calling this unhealthy dependency?"
SagaMicroservicesDistributed transaction managementT1 → T2 → T3 fails → C2 → C1"How do I keep business data consistent across services when one step fails?"

#Super-Short Memory Trick

PatternWord
Factory MethodCreate
SingletonOne
BuilderBuild
StrategyChoose
ObserverNotify
ProxyControl
AdapterConvert / connect
DecoratorEnhance
Circuit BreakerProtect
SagaCompensate

#Pattern Categories

  • Patterns in this topic
    • Creational
      • Factory Method
      • Singleton
      • Builder
    • Structural
      • Proxy
      • Adapter
      • Decorator
    • Behavioral
      • Strategy
      • Observer
    • Microservices / distributed
      • Circuit Breaker
      • Saga

#Key Flows

Circuit Breaker

CLOSED
OPEN
HALF_OPEN — trial call succeeds?
CLOSED
OPEN

Saga

T1 Create Order
T2 Payment
T3 Inventory fails
C2 Refund Payment
C1 Cancel Order

Two styles: choreography (events, no central boss) and orchestration (a central orchestrator).

#One-Line Interview Definitions

  • Factory Method — defines an interface or method for creating an object while letting subclasses decide which concrete product to create.
  • Singleton — ensures that a class has only one instance and provides controlled access to it.
  • Builder — constructs complex objects step by step, separating construction from the final object.
  • Strategy — encapsulates interchangeable algorithms behind a common interface and allows behaviour to be selected at runtime.
  • Observer — defines a one-to-many relationship in which observers are notified when the subject changes.
  • Proxy — provides a substitute for another object to control access to it.
  • Adapter — converts one interface into another interface expected by the client.
  • Decorator — adds responsibilities dynamically by wrapping an object with another object implementing the same abstraction.
  • Circuit Breaker — prevents cascading failures by temporarily stopping calls to an unhealthy dependency and later testing recovery.
  • Saga — maintains business consistency across multiple services using a sequence of local transactions, with compensating transactions when later steps fail.

#Look-Alike Patterns

CompareDifference
Proxy vs DecoratorSame interface for both. Proxy controls access (often created by a framework); Decorator adds behaviour and is stacked by the client
Adapter vs DecoratorAdapter changes the interface; Decorator keeps it
Adapter vs ProxyAdapter presents a different interface; Proxy presents the same one
Strategy vs StateStrategy is chosen by the client; State changes itself as internal state changes
Factory vs BuilderFactory decides which object; Builder controls how one complex object is assembled
Factory Method vs Abstract FactoryOne product via a subclass-overridden method vs a family of related products from one factory object
Observer vs Pub/SubDirect in-process notification vs decoupled via a broker across services
Saga vs 2PCLocal transactions + compensations, eventual consistency vs one global locking transaction

#Patterns You Use Every Day in Spring

PatternWhere in Spring
SingletonDefault bean scope
FactoryBeanFactory, FactoryBean, @Bean methods
BuilderResponseEntity, UriComponentsBuilder, WebClient.builder()
StrategyInjecting List<Interface> / Map<String, Interface>; PasswordEncoder
ObserverApplicationEventPublisher + @EventListener
Proxy@Transactional, @Cacheable, @Async, Spring AOP
AdapterHandlerAdapter in Spring MVC
DecoratorTransactionAwareDataSourceProxy, request wrappers
Circuit BreakerResilience4j @CircuitBreaker
SagaOrchestrated with Temporal / Camunda, or choreographed with Kafka events

#Practice Problems

Easy

  1. Implement a thread-safe singleton three different ways.
  2. Write a Pizza builder with required size and optional toppings, validated in build().
  3. Replace an if/else chain of discount types with Strategy.
  4. Wrap a third-party LegacySmsApi with an adapter for your SmsSender interface.

Medium

  1. Implement a stock-price subject with thread-safe observers.
  2. Write a caching proxy for a slow ProductRepository.
  3. Decorate a DataSource-like interface with logging and timing decorators.
  4. Build a notification factory that selects email, SMS or push by configuration.

Interview level

  1. Implement a thread-safe circuit breaker that allows only one trial call in HALF_OPEN.
  2. Design an orchestrated saga for hotel + flight + car booking, with compensations and idempotency.
  3. Explain, with code, how Spring's @Transactional uses the Proxy pattern and why self-invocation breaks it.
  4. Show how Strategy and Factory work together to choose a payment method at runtime in Spring.

#Key Takeaways

  • Creational: Factory Method (create), Singleton (one), Builder (build).
  • Structural: Proxy (control), Adapter (convert), Decorator (enhance).
  • Behavioral: Strategy (choose), Observer (notify).
  • Microservices: Circuit Breaker (protect), Saga (compensate).
  • Know each pattern's problem, its look-alikes, and where Spring uses it.