7

Quick Reference

One-page per pattern. Print-friendly.

WHICH PATTERN? DECISION FLOWCHART

Need to CREATE objects? → How many types?

One type, complex build → Builder

Multiple types, same interface → Factory Method

Families of related types → Abstract Factory

Only one instance → Singleton (or DI scope)

Need to STRUCTURE relationships?

Make incompatible interfaces work → Adapter

Simplify a complex subsystem → Facade

Add behavior without modifying → Decorator

Control access to an object → Proxy

Part-whole tree → Composite

Need to manage BEHAVIOR?

Swap algorithms → Strategy

Object changes behavior based on state → State

Notify many listeners → Observer

Pipeline of handlers → Chain of Responsibility

Queue, undo, log actions → Command

Same skeleton, different steps → Template Method

No pattern fits? A function or a simple class is fine. Do not force it.

Factory Method

Creational
Trigger: "create different types based on..."
UML:
Creator → Product
ConcreteCreator → ConcreteProduct
Code:
abstract createProduct(): Product
Don't use when: When there is only one type to create — use new directly.

Strategy

Behavioral
Trigger: "switch between algorithms" or "different ways to..."
UML:
Context → Strategy
ConcreteStrategyA, ConcreteStrategyB
Code:
ctx.setStrategy(new ConcreteStrategy())
ctx.execute()
Don't use when: When you have only one algorithm and it will never change.

Observer

Behavioral
Trigger: "notify all", "when X changes, update Y"
UML:
Subject → Observer[]
ConcreteObserverA, ConcreteObserverB
Code:
subject.subscribe(observer)
subject.notify()
Don't use when: When the notification order matters critically, or when there is only one listener.

Decorator

Structural
Trigger: "add behavior without modifying", "wrap", "middleware"
UML:
Component → ConcreteComponent
Decorator → Component (wraps)
Code:
new LoggingDecorator(new RateLimiter(handler))
Don't use when: When you need to remove decorators at runtime or the wrapping order is fragile.

State

Behavioral
Trigger: "behaves differently depending on state", "transitions"
UML:
Context → State
ConcreteStateA, ConcreteStateB
Code:
this.state = new PaidState()
this.state.handle()
Don't use when: When there are only 2-3 states with trivial logic — an if/switch is simpler.

Builder

Creational
Trigger: "complex object with many optional parts"
UML:
Director → Builder
ConcreteBuilder → Product
Code:
new Builder().setX(a).setY(b).build()
Don't use when: When the object has few required fields — just use a constructor.

Adapter

Structural
Trigger: "incompatible interface", "legacy system", "third-party"
UML:
Client → Target
Adapter → Adaptee
Code:
class StripeAdapter implements PaymentGateway { ... }
Don't use when: When you control both sides — change the interface instead.

Facade

Structural
Trigger: "simplify", "one entry point to a complex subsystem"
UML:
Facade → SubsystemA, SubsystemB, SubsystemC
Code:
orderFacade.placeOrder(cart, payment, shipping)
Don't use when: When the subsystem is already simple, or when clients need fine-grained control.

Command

Behavioral
Trigger: "undo", "queue", "log operations", "macro"
UML:
Invoker → Command
ConcreteCommand → Receiver
Code:
cmd.execute(); history.push(cmd); cmd.undo()
Don't use when: When operations are simple and don't need undo/queue.

Chain of Responsibility

Behavioral
Trigger: "pipeline", "middleware", "pass to next handler"
UML:
Handler → Handler (next)
ConcreteHandlerA, ConcreteHandlerB
Code:
handler.setNext(auth).setNext(validate).setNext(process)
Don't use when: When the processing order is fixed and there is only one handler.

Proxy

Structural
Trigger: "control access", "lazy load", "cache", "protect"
UML:
Client → Subject
Proxy → RealSubject
Code:
class CachingProxy implements Repository { ... }
Don't use when: When there is no access control, caching, or lazy-loading need.

Singleton

Creational
Trigger: "only one instance", "global state"
UML:
Singleton (private constructor, static instance)
Code:
class DB { static instance: DB; static get() { ... } }
Don't use when: Almost always — prefer DI-managed singletons for testability.

Abstract Factory

Creational
Trigger: "families of related objects", "must be from same provider"
UML:
AbstractFactory → ProductA, ProductB
ConcreteFactory1, ConcreteFactory2
Code:
factory.createRepo(); factory.createMigration()
Don't use when: When you only need one product type — use Factory Method instead.

Template Method

Behavioral
Trigger: "same steps, different details", "skeleton algorithm"
UML:
AbstractClass (templateMethod, step1, step2)
ConcreteClass overrides steps
Code:
abstract class Report { generate() { fetch(); validate(); render(); } }
Don't use when: When only one step varies — Strategy with composition is simpler.

Composite

Structural
Trigger: "tree structure", "folders and files", "groups containing groups"
UML:
Component → Leaf, Composite
Composite contains Component[]
Code:
group.getPrice() // sums children recursively
Don't use when: When the hierarchy is flat or only 2 levels deep.

Mediator

Behavioral
Trigger: "coordinate between many objects", "central hub"
UML:
Mediator → Colleague[]
Colleague → Mediator
Code:
chatRoom.send(userId, message, targetId)
Don't use when: When communication is one-to-many (use Observer instead).

Bridge

Structural
Trigger: "two dimensions that vary independently"
UML:
Abstraction → Implementation
RefinedAbstraction, ConcreteImplementation
Code:
new AlertNotification(new EmailChannel())
Don't use when: When only one dimension varies — just use an interface.

Dependency Injection

Extra
Trigger: "testable", "swappable dependencies", "constructor injection"
UML:
Client → Interface ← Implementation
Container wires them
Code:
constructor(private readonly repo: UserRepository) {}
Don't use when: For simple scripts or utilities with no dependencies to swap.

Repository

Extra
Trigger: "abstract database access", "switch databases"
UML:
Service → Repository (interface)
TypeORMRepository, PrismaRepository
Code:
interface UserRepo { findById(id): User; save(user): void }
Don't use when: When you're doing simple CRUD and the ORM is the repo.

Event Bus / Pub-Sub

Extra
Trigger: "decouple services", "async events", "microservices"
UML:
Publisher → Broker → Subscriber[]
Topics route messages
Code:
eventBus.publish('order.placed', order)
eventBus.subscribe('order.placed', handler)
Don't use when: When you need synchronous, guaranteed ordering — use direct calls.

Circuit Breaker

Extra
Trigger: "downstream failures", "cascading", "resilience"
UML:
Closed → Open → HalfOpen
Trips after N failures
Code:
const breaker = new CircuitBreaker(apiCall, { threshold: 5 })
Don't use when: For calls to local, always-available resources.