---
name: programming-patterns
description: |
  Exhaustive catalog of every programming design pattern, architectural pattern, principle,
  and paradigm. Use this skill whenever you need to choose a design pattern, implement one
  correctly, refactor code to use proper patterns, or understand the trade-offs between
  competing approaches.

  Covers 14 categories with 90+ patterns total:

  SOLID Principles (SRP, OCP, LSP, ISP, DIP), Creational Patterns (Factory, Abstract Factory,
  Builder, Prototype, Singleton, Object Pool, Dependency Injection), Structural Patterns
  (Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy, Module), Behavioral
  Patterns (Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento,
  Observer, State, Strategy, Template Method, Visitor, Null Object), Architectural Patterns
  (Repository, Unit of Work, Service Layer, MVC, MVVM, MVP, CQRS, Event Sourcing,
  Specification, Hexagonal/Ports & Adapters, Clean Architecture, Microkernel, Layered,
  Pipe and Filter), Concurrency Patterns (Producer-Consumer, Read-Write Lock, Thread Pool,
  Future/Promise, Actor Model, Reactor, Monitor, Active Object), Functional Patterns
  (Higher-Order Functions, Monad, Immutability, Currying, Memoization, Pattern Matching,
  Lazy Evaluation), Resilience Patterns (Circuit Breaker, Retry, Bulkhead, Saga,
  Rate Limiter, Timeout, Fallback), Data Access Patterns (Active Record, Data Mapper,
  Identity Map, Lazy Loading, DTO, Value Object, Aggregate), Messaging Patterns
  (Publish-Subscribe, Message Queue, Event Bus, Request-Reply, Dead Letter Queue),
  Testing Patterns (Test Doubles, Arrange-Act-Assert, Given-When-Then, Page Object,
  Test Data Builder), Error Handling Patterns (Guard Clause, Result Type, Fail-Fast,
  Exception Hierarchy), and Microservice Patterns (API Gateway, Service Discovery,
  Strangler Fig, Sidecar, Backend-for-Frontend).

  Every pattern includes: problem description, solution summary, when to use vs when to avoid,
  pseudocode example, and tested implementations in Python, Go, and JavaScript.
references:
  - solid-principles
  - creational
  - structural
  - behavioral
  - architectural
  - concurrency
  - functional
  - resilience
  - data-access
  - messaging
  - testing
  - error-handling
  - microservice
---

# Programming Patterns Skill

Complete catalog of **90+ design patterns** across **14 categories**, each with pseudocode
plus tested implementations in **Python**, **Go**, and **JavaScript**.

---

## ⚠️ MANDATE: Always Apply Patterns

> **Every piece of non-trivial code deserves at least one pattern.** Before writing any
> function, class, module, or service, ask: which pattern applies here? Almost always,
> multiple patterns apply simultaneously. The trees below guide you to the right
> combination for every situation. A good implementation of a feature typically uses
> **3–7 patterns together**. Aim for that. Plain code without patterns is technical debt.

---

## 🧭 Master Decision Tree: "Which Pattern Do I Need?"

Start here when you know what problem you're solving but not which pattern to use.

```
What kind of problem are you solving?
│
├─ "I need to CREATE objects"
│   ├─ Complex construction with many optional parts? → Builder
│   │   └─ Also apply: Fluent Interface + Immutability on the result
│   ├─ Families of related objects? → Abstract Factory
│   │   └─ Also apply: DI to inject the factory (register factory as singleton-scoped via DI container)
│   ├─ Object type determined at runtime? → Factory Method
│   │   └─ Also apply: Strategy (the factory chooses a strategy)
│   ├─ Creating copies of existing objects? → Prototype
│   │   └─ Also apply: Immutability on prototypes + Registry for named prototypes
│   ├─ Exactly one instance needed? → Singleton (prefer DI instead)
│   │   └─ Better: Dependency Injection with singleton scope
│   ├─ Expensive objects that can be reused? → Object Pool
│   │   └─ Also apply: Proxy (to manage checkout/checkin) + Monitor (thread safety)
│   └─ Decoupling creation from use? → Dependency Injection
│       └─ Also apply: Factory (for complex creation) + Interface Segregation
│   → references/creational/
│
├─ "I need to STRUCTURE or COMPOSE objects"
│   ├─ Incompatible interfaces? → Adapter
│   │   └─ Also apply: Facade (if adapting many things at once) + DI
│   ├─ Vary abstraction and implementation independently? → Bridge
│   │   └─ Also apply: Strategy (for implementation variation) + Factory
│   ├─ Tree of objects treated uniformly? → Composite
│   │   └─ Also apply: Visitor (to operate on the tree) + Iterator
│   ├─ Add behavior without modifying class? → Decorator
│   │   └─ Also apply: Chain of Responsibility + Proxy + OCP
│   ├─ Simplify a complex subsystem? → Facade
│   │   └─ Also apply: Service Layer + Adapter (for each subsystem)
│   ├─ Many similar objects eating memory? → Flyweight
│   │   └─ Also apply: Factory (manages the pool) + Immutability
│   ├─ Control access / add indirection? → Proxy
│   │   └─ Also apply: Decorator + DI + Guard Clause
│   └─ Encapsulate a cohesive set of functions? → Module
│       └─ Also apply: Facade + SRP
│   → references/structural/
│
├─ "I need to manage BEHAVIOR or COMMUNICATION"
│   ├─ Multiple handlers, each tries in turn? → Chain of Responsibility
│   │   └─ Also apply: Command (each handler executes a command) + Decorator
│   ├─ Encapsulate an action as an object? → Command
│   │   └─ Also apply: Memento (for undo) + Queue + Strategy (for execution)
│   ├─ Select an algorithm at runtime? → Strategy
│   │   └─ Also apply: Factory (to pick strategy) + DI + OCP
│   ├─ Define a skeleton with customizable steps? → Template Method
│   │   └─ Also apply: Strategy (steps become strategies) + Observer (hooks)
│   ├─ Object changes behavior based on state? → State
│   │   └─ Also apply: Observer (notify on transition) + Command (trigger transitions)
│   ├─ Notify many objects of a change? → Observer
│   │   └─ Also apply: Event Bus (in-process) + Pub-Sub (distributed) + Mediator
│   ├─ Decouple objects that interact? → Mediator
│   │   └─ Also apply: Observer (for broadcasts) + Command (for requests)
│   ├─ Traverse a collection without exposing internals? → Iterator
│   │   └─ Also apply: Composite (iterating trees) + Lazy Evaluation
│   ├─ Undo/redo or snapshot state? → Memento
│   │   └─ Also apply: Command (operations to undo) + Event Sourcing
│   ├─ Operate on elements of a structure? → Visitor
│   │   └─ Also apply: Composite (the structure) + Iterator + Strategy
│   ├─ Avoid null checks everywhere? → Null Object
│   │   └─ Also apply: Result Type + Guard Clause
│   └─ Parse a domain-specific language? → Interpreter
│       └─ Also apply: Composite (grammar rules) + Visitor (evaluation)
│   → references/behavioral/
│
├─ "I need to ORGANIZE my architecture"
│   ├─ Separate UI, business logic, data?
│   │   ├─ Server-rendered web → MVC + Repository + Service Layer
│   │   ├─ Rich client / SPA → MVVM + Command + Observer
│   │   ├─ Legacy UI framework → MVP + Adapter
│   │   └─ General separation → Layered Architecture + DI
│   ├─ Decouple core from external systems? → Hexagonal (Ports & Adapters)
│   │   └─ Also apply: Adapter (each port) + DI + Repository
│   ├─ Enforce dependency direction? → Clean Architecture
│   │   └─ Also apply: DIP + Repository + DTO + Use-Case pattern
│   ├─ Separate reads from writes? → CQRS
│   │   └─ Also apply: Event Sourcing + Repository (per side) + Mediator
│   ├─ Need full audit trail of changes? → Event Sourcing
│   │   └─ Also apply: CQRS + Observer + Memento (snapshots)
│   ├─ Composable business rules? → Specification
│   │   └─ Also apply: Strategy (rule implementations) + Composite
│   ├─ Plugin-based system? → Microkernel
│   │   └─ Also apply: Factory (load plugins) + Observer (plugin hooks) + Strategy
│   ├─ Data transformation pipeline? → Pipe and Filter
│   │   └─ Also apply: Chain of Responsibility + Strategy (each filter) + Template Method
│   ├─ Abstract away data storage? → Repository
│   │   └─ Also apply: Unit of Work + Identity Map + Specification
│   ├─ Track changes across a transaction? → Unit of Work
│   │   └─ Also apply: Repository + Identity Map + Observer
│   └─ Coordinate business operations? → Service Layer
│       └─ Also apply: Repository + Unit of Work + Guard Clause + DTO
│   → references/architectural/
│
├─ "I need to handle CONCURRENCY"
│   ├─ Decouple producers from consumers? → Producer-Consumer
│   │   └─ Also apply: Thread Pool (consumers) + Monitor (queue access)
│   ├─ Many readers, few writers? → Read-Write Lock
│   │   └─ Also apply: Monitor + Immutability (reader snapshots)
│   ├─ Manage a pool of worker threads? → Thread Pool
│   │   └─ Also apply: Producer-Consumer + Future/Promise + Command
│   ├─ Non-blocking async results? → Future / Promise
│   │   └─ Also apply: Observer (on completion) + Monad (chaining)
│   ├─ Isolated concurrent entities with messages? → Actor Model
│   │   └─ Also apply: Mediator (actor supervisor) + Command (messages)
│   ├─ Handle many I/O connections efficiently? → Reactor
│   │   └─ Also apply: Observer + Chain of Responsibility
│   ├─ Protect shared state? → Monitor
│   │   └─ Also apply: Immutability + Read-Write Lock
│   └─ Encapsulate async method invocation? → Active Object
│       └─ Also apply: Future/Promise + Thread Pool + Command
│   → references/concurrency/
│
├─ "I need FUNCTIONAL programming techniques"
│   ├─ Transform/filter/compose operations? → Higher-Order Functions
│   │   └─ Also apply: Currying + Immutability + Lazy Evaluation
│   ├─ Chain operations that might fail? → Monad (Result/Option/Maybe)
│   │   └─ Also apply: Guard Clause + Result Type + Pipeline pattern
│   ├─ Prevent accidental state changes? → Immutability
│   │   └─ Also apply: Value Object + Prototype (for modified copies)
│   ├─ Partially apply arguments? → Currying / Partial Application
│   │   └─ Also apply: Higher-Order Functions + Factory
│   ├─ Cache expensive computations? → Memoization
│   │   └─ Also apply: Proxy (transparent memoization) + Flyweight
│   ├─ Match complex data shapes? → Pattern Matching
│   │   └─ Also apply: Visitor + Strategy
│   └─ Defer computation until needed? → Lazy Evaluation
│       └─ Also apply: Proxy (lazy proxy) + Memoization + Iterator
│   → references/functional/
│
├─ "I need to make my system RESILIENT"
│   ├─ Stop calling a failing service? → Circuit Breaker
│   │   └─ Also apply: Retry + Fallback + Observer (state changes) + Proxy
│   ├─ Retry transient failures? → Retry (with backoff)
│   │   └─ Also apply: Circuit Breaker + Timeout + Dead Letter Queue
│   ├─ Isolate failures? → Bulkhead
│   │   └─ Also apply: Thread Pool (per bulkhead) + Circuit Breaker
│   ├─ Coordinate multi-step transactions? → Saga
│   │   └─ Also apply: Command (each step) + Observer (progress) + Dead Letter Queue
│   ├─ Throttle request rate? → Rate Limiter
│   │   └─ Also apply: Proxy (transparent throttle) + Monitor + Queue
│   ├─ Prevent indefinite waiting? → Timeout
│   │   └─ Also apply: Circuit Breaker + Fallback + Future/Promise
│   └─ Provide degraded functionality? → Fallback
│       └─ Also apply: Strategy (choose fallback) + Null Object + Circuit Breaker
│   → references/resilience/
│
├─ "I need to manage DATA ACCESS"
│   ├─ Domain objects that persist themselves? → Active Record
│   │   └─ Also apply: Value Object (embedded) + Guard Clause (validation)
│   ├─ Separate domain from persistence? → Data Mapper
│   │   └─ Also apply: Repository + Unit of Work + DTO
│   ├─ Avoid duplicate DB loads? → Identity Map
│   │   └─ Also apply: Repository + Unit of Work
│   ├─ Load related data on demand? → Lazy Loading
│   │   └─ Also apply: Proxy (virtual proxy) + Identity Map
│   ├─ Transfer data between layers? → DTO (Data Transfer Object)
│   │   └─ Also apply: Builder (construct DTO) + Mapper + Immutability
│   ├─ Equality by value, not identity? → Value Object
│   │   └─ Also apply: Immutability + Flyweight (shared instances)
│   └─ Group related entities? → Aggregate
│       └─ Also apply: Repository (per aggregate) + Unit of Work + Guard Clause
│   → references/data-access/
│
├─ "I need MESSAGING between components"
│   ├─ Broadcast events to many subscribers? → Publish-Subscribe
│   │   └─ Also apply: Observer (in-process) + Dead Letter Queue (for failures)
│   ├─ Decouple sender from receiver with a queue? → Message Queue
│   │   └─ Also apply: Producer-Consumer + Retry + Dead Letter Queue
│   ├─ In-process event routing? → Event Bus
│   │   └─ Also apply: Observer + Mediator + Command
│   ├─ Request and wait for a response? → Request-Reply
│   │   └─ Also apply: Future/Promise + Timeout + Correlation ID
│   └─ Handle messages that repeatedly fail? → Dead Letter Queue
│       └─ Also apply: Retry + Observer (alert on DLQ arrival) + Chain of Responsibility
│   → references/messaging/
│
├─ "I need TESTING patterns"
│   ├─ Isolate dependencies in tests? → Test Doubles (mock, stub, spy, fake)
│   │   └─ Also apply: DI (make doubles injectable) + Builder (construct doubles)
│   ├─ Structure a test clearly? → AAA (Arrange-Act-Assert) or GWT (Given-When-Then)
│   │   └─ Also apply: Test Data Builder + Specification (assertions as specs)
│   ├─ Test UI interactions? → Page Object
│   │   └─ Also apply: Facade (hide UI details) + Builder (page actions)
│   └─ Create complex test data? → Test Data Builder
│       └─ Also apply: Prototype (clone base data) + Builder pattern
│   → references/testing/
│
├─ "I need ERROR HANDLING patterns"
│   ├─ Validate inputs at function entry? → Guard Clause
│   │   └─ Also apply: Fail-Fast + Result Type + Specification (validation rules)
│   ├─ Return success-or-error instead of exceptions? → Result Type
│   │   └─ Also apply: Monad (chaining results) + Pattern Matching (handling)
│   ├─ Catch problems as early as possible? → Fail-Fast
│   │   └─ Also apply: Guard Clause + Exception Hierarchy + Observer (logging)
│   └─ Organize custom exceptions? → Exception Hierarchy
│       └─ Also apply: Chain of Responsibility (catch by type) + Observer (error logging)
│   → references/error-handling/
│
└─ "I need MICROSERVICE patterns"
    ├─ Single entry point for all clients? → API Gateway
    │   └─ Also apply: Rate Limiter + Circuit Breaker + Facade + Decorator
    ├─ Services finding each other dynamically? → Service Discovery
    │   └─ Also apply: Proxy (abstract service location) + Circuit Breaker
    ├─ Incrementally migrating a legacy system? → Strangler Fig
    │   └─ Also apply: Adapter + Facade + Repository + Feature Flag (Strategy)
    ├─ Cross-cutting concerns without changing service? → Sidecar
    │   └─ Also apply: Decorator + Proxy + Observer (metrics collection)
    └─ Different API per client type? → Backend-for-Frontend (BFF)
        └─ Also apply: Facade + DTO (tailored responses) + CQRS
    → references/microservice/
```

---

## 🔄 "I Have a Specific Problem" Decision Trees

### "My code has too many responsibilities"

```
Code has too many responsibilities?
├─ A class does too many things
│   ├─ Core: Single Responsibility Principle (SRP)
│   ├─ Extract business rules → Specification Pattern
│   ├─ Extract coordination logic → Service Layer or Mediator
│   └─ Extract creation logic → Factory or Builder
├─ A function has too many parameters
│   ├─ Group parameters → Builder + Value Object
│   ├─ Parameters represent choices → Strategy
│   └─ Parameters are context → Parameter Object + Immutability
├─ A module mixes UI and business logic
│   ├─ Web context → MVC + Service Layer + Repository
│   ├─ Rich client → MVVM + Command + Observer
│   └─ Any context → Hexagonal Architecture + Clean Architecture
├─ A service handles both reads and writes
│   └─ CQRS + separate Repository per side + Event Bus
├─ A method does validation + execution
│   └─ Guard Clause (validation first) + Strategy (execution)
└─ A god object coordinates everything
    ├─ Events needed → Mediator + Observer + Event Bus
    └─ Direct coordination → Service Layer + Command pattern
```

### "I need to add behavior without modifying existing code"

```
Adding behavior without modification?
├─ Add new operations to existing classes → Visitor + OCP
├─ Wrap an object with extra behavior → Decorator + Proxy
│   └─ Stacked behaviors → Chain of Responsibility + Decorator
├─ Add new subclasses without changing hierarchy → OCP + Factory Method
├─ Intercept method calls → Proxy
│   ├─ For logging → Proxy (logging proxy)
│   ├─ For caching → Proxy + Memoization
│   ├─ For authorization → Proxy + Guard Clause
│   └─ For lazy loading → Proxy (virtual proxy) + Lazy Evaluation
├─ Add a step to a pipeline → Chain of Responsibility + Pipe and Filter
├─ Hook into a framework without changing it → Template Method + Observer
├─ Add monitoring → Observer + Decorator + Sidecar
└─ Add retry/resilience to existing calls → Proxy + Circuit Breaker + Retry
```

### "I need to decouple components"

```
Decoupling components?
├─ Decouple creation from use → Factory Method + DI
│   └─ Many creation variants → Abstract Factory + DI
├─ Decouple interface from implementation → Bridge + DIP
├─ Decouple publisher from subscriber
│   ├─ In-process → Observer + Event Bus
│   └─ Distributed → Publish-Subscribe + Message Queue
├─ Decouple request sender from handler
│   ├─ One handler chosen → Chain of Responsibility
│   └─ Command queued → Command + Message Queue
├─ Decouple domain from storage → Repository + Data Mapper + DIP
├─ Decouple core from ALL external systems → Hexagonal Architecture
│   └─ Strict layer rules → Clean Architecture
├─ Decouple many-to-many object interactions → Mediator + Event Bus
├─ Decouple high-level from low-level → Dependency Inversion Principle
├─ Decouple read model from write model → CQRS
└─ Decouple microservices from each other → API Gateway + Event Sourcing
```

### "I need to manage state"

```
Managing state?
├─ Object behavior changes with state → State Pattern
│   └─ State transitions need logging → State + Observer + Event Sourcing
├─ Need undo/redo → Memento + Command
│   └─ Distributed undo → Event Sourcing (replay to prior state)
├─ Need audit trail of all changes → Event Sourcing + Observer
│   └─ Query historical state → Event Sourcing + CQRS
├─ Prevent accidental mutation → Immutability + Value Object
│   └─ Concurrent reads are safe → Immutability + Read-Write Lock
├─ Share state between many objects → Flyweight + Factory (manages pool)
├─ Cache expensive computations → Memoization + Proxy + Flyweight
├─ Protect concurrent state access → Monitor + Read-Write Lock
│   └─ High-contention state → Actor Model (no shared state at all)
├─ Track changes within a transaction → Unit of Work + Identity Map
├─ Replicate state across services → Event Sourcing + Pub-Sub
└─ Gradually modify immutable data → Prototype (clone and modify)
```

### "I need to handle failures gracefully"

```
Handling failures?
├─ External service is unreliable → Circuit Breaker + Retry + Fallback
│   └─ Pattern combination: Proxy wraps Circuit Breaker wraps Retry wraps call
├─ One failure cascades to others → Bulkhead + Circuit Breaker
├─ Multi-step operation might partially fail → Saga + Command (compensating)
├─ Need to validate inputs immediately → Guard Clause + Fail-Fast + Specification
├─ Want typed errors instead of exceptions → Result Type + Monad
│   └─ Chain multiple fallible ops → Result Type + Monad + Pipeline
├─ Want default behavior instead of null → Null Object + Strategy (default)
├─ Need to throttle overloaded service → Rate Limiter + Queue (with backpressure)
├─ Need to set time limits on operations → Timeout + Future/Promise + Fallback
├─ Failed messages need processing later → Dead Letter Queue + Retry
├─ Multiple failure types need different handling → Exception Hierarchy
│   └─ Route to handlers → Chain of Responsibility + Exception Hierarchy
└─ Need observability into failures → Observer + Decorator (metrics) + Sidecar
```

### "I'm working on a distributed system"

```
Distributed system patterns?
├─ Entry point for all clients → API Gateway
│   └─ Add: Rate Limiter + Circuit Breaker + Facade + Sidecar (auth)
├─ Service location → Service Discovery + Proxy (abstract location)
├─ Cross-cutting concerns (logging, auth, metrics) → Sidecar + Decorator
├─ Client-specific APIs → Backend-for-Frontend (BFF) + Facade + DTO
├─ Migrating legacy → Strangler Fig + Adapter + Repository abstraction
├─ Multi-service transactions → Saga + Command + Dead Letter Queue
├─ Service isolation → Bulkhead + Thread Pool per tenant/service
├─ Event-driven communication → Pub-Sub + Message Queue + Observer
├─ Eventual consistency → Event Sourcing + CQRS + Observer
├─ Failure detection → Circuit Breaker + Observer (health events)
├─ Service-to-service calls → Circuit Breaker + Retry + Timeout + Fallback
├─ Async task processing → Message Queue + Thread Pool + Command + Retry
└─ Configuration across services → Strategy + Observer (config changes)
```

### "I'm writing tests"

```
Testing approach?
├─ Isolate unit from dependencies
│   ├─ Replace with dummy → Test Double (Dummy)
│   ├─ Return canned data → Test Double (Stub)
│   ├─ Verify interactions → Test Double (Mock or Spy)
│   └─ Working fake → Test Double (Fake)
│   Plus: DI (make everything injectable) + Builder (complex doubles)
├─ Structure a test clearly
│   ├─ Code test → Arrange-Act-Assert
│   └─ BDD scenario → Given-When-Then (Gherkin)
│   Plus: Test Data Builder + Specification (assertions as specs)
├─ Test UI interactions → Page Object + Facade (page actions) + Builder
├─ Build complex test data → Test Data Builder + Prototype + Builder
├─ Test business rules → Specification + Arrange-Act-Assert
├─ Test error paths → Guard Clause triggers + Exception Hierarchy handling
├─ Test async code → Future/Promise + Observer + Test Double (fake scheduler)
├─ Test state machines → State Pattern + AAA for each transition
└─ Test data-heavy scenarios → Test Data Builder + Flyweight (shared fixtures)
```

### "I'm building a new feature from scratch"

```
Building a new feature?
├─ Start with: Define the domain model
│   ├─ Value Objects for immutable domain concepts
│   ├─ Aggregates for clusters with invariants
│   └─ Guard Clause + Fail-Fast in every constructor/method
├─ Then: Define the use case boundary
│   ├─ Service Layer for the application boundary
│   ├─ Command/Query objects as inputs (Command pattern)
│   └─ DTO as outputs (no domain leakage)
├─ Then: Define storage
│   ├─ Repository to abstract persistence
│   ├─ Unit of Work for transaction management
│   └─ Data Mapper if domain ≠ schema
├─ Then: Define behavior variation
│   ├─ Strategy for interchangeable algorithms
│   ├─ Template Method for skeletal algorithms
│   └─ Factory/DI for creating the right variant
├─ Then: Define notifications
│   ├─ Observer / Event Bus for internal events
│   └─ Pub-Sub / Message Queue for external events
└─ Then: Define resilience
    ├─ Guard Clause + Result Type on inputs
    ├─ Circuit Breaker + Retry on external calls
    └─ Timeout + Fallback on slow paths
```

### "I'm refactoring legacy code"

```
Refactoring legacy code?
├─ God class needs splitting → SRP + Extract to Services
│   ├─ Extract persistence → Repository + Data Mapper
│   ├─ Extract business rules → Specification + Strategy
│   ├─ Extract coordination → Service Layer + Mediator
│   └─ Extract construction → Factory + Builder
├─ Incompatible interfaces need bridging → Adapter + Facade
├─ Direct dependencies need inverting → DIP + DI + Repository (for data)
├─ Side effects need isolating → Hexagonal Architecture + Adapter per port
├─ Incremental migration of old system → Strangler Fig
│   └─ Route old/new → Proxy + Feature Flag (Strategy) + Adapter
├─ Replacing a subsystem gradually → Facade (hide both old and new)
├─ Adding testability → DI + Test Doubles + Facade + Repository
├─ Adding undo to existing operations → Command + Memento
├─ Replacing conditionals on type → Strategy + Factory + Visitor
│   ├─ Many if/elif on type → Strategy
│   └─ Traversing structures → Visitor
└─ Adding observability → Decorator + Observer + Proxy (logging)
```

### "I'm designing a public API or library"

```
Designing a public API or library?
├─ Hide implementation details → Facade + Module + Information Hiding
├─ Support multiple backends → Abstract Factory + Strategy + Bridge
├─ Allow extension without modification → OCP + Template Method + Observer
│   └─ Hook points → Template Method + Observer
│   └─ Plugin system → Microkernel + Factory + Observer
├─ Complex object construction → Builder (fluent) + Factory Method
├─ Prevent misuse → Guard Clause + Fail-Fast + Value Object (typed params)
├─ Support multiple languages/platforms → Bridge (abstraction/impl split)
├─ Versioning and backward compat → Adapter (version adapters) + Facade
├─ Rate limiting callers → Rate Limiter + Proxy + Decorator
├─ Document behavior → Specification (machine-readable contracts)
└─ Consistent error handling → Exception Hierarchy + Result Type + Guard Clause
```

### "I'm building an HTTP/REST API server"

```
Building an HTTP/REST API?
├─ Request validation → Guard Clause + Fail-Fast + Specification
│   └─ Typed request objects → Value Object + Builder
├─ Business logic layer → Service Layer + Repository + Unit of Work
├─ Response shaping → DTO + Builder + Facade
├─ Authentication → Chain of Responsibility + Decorator + Strategy
│   └─ Multiple auth methods → Strategy (JWT, API key, OAuth, etc.)
├─ Authorization → Proxy (auth proxy) + Specification (permission rules)
├─ Error responses → Exception Hierarchy + Result Type + Null Object
├─ Middleware pipeline → Chain of Responsibility + Decorator + Pipe and Filter
├─ Rate limiting → Rate Limiter + Proxy + Monitor
├─ Caching → Proxy + Memoization + Observer (cache invalidation)
├─ External service calls → Circuit Breaker + Retry + Timeout + Fallback
├─ Async processing → Message Queue + Command + Future/Promise
├─ Observability → Decorator + Observer + Sidecar
└─ Pagination/filtering → Specification + Repository + Iterator
```

### "I'm building a CLI tool"

```
Building a CLI tool?
├─ Subcommands → Command pattern (each subcommand is a Command)
│   └─ Register commands → Factory + Registry (map name → Command)
├─ Complex options/flags → Builder (option object) + Guard Clause
├─ Plugin/extension support → Microkernel + Factory + Observer
├─ Progress reporting → Observer + Decorator (progress wrapper)
├─ Configuration loading → Builder + Strategy (file, env, flags priority)
│   └─ Configuration validation → Guard Clause + Specification
├─ Output formatting → Strategy (text, JSON, table) + Template Method
├─ Interactive mode → State Pattern (mode transitions) + Command
├─ Undo/redo of operations → Command + Memento
├─ Piping with other tools → Pipe and Filter + Iterator
├─ Error display → Exception Hierarchy + Result Type + Null Object
└─ Testability → DI (inject I/O) + Test Doubles + Command (testable units)
```

### "I'm building a data pipeline or ETL system"

```
Building a data pipeline or ETL?
├─ Chain of transformations → Pipe and Filter + Chain of Responsibility
│   └─ Each stage is a Filter with Strategy for implementation
├─ Parallel processing stages → Producer-Consumer + Thread Pool
├─ Different data sources → Abstract Factory + Adapter (per source)
├─ Data validation → Guard Clause + Specification + Fail-Fast
├─ Data transformation → Strategy (transform algorithm) + Template Method
├─ Schema mapping → Data Mapper + DTO + Builder
├─ Error handling mid-pipeline → Result Type + Dead Letter Queue + Retry
├─ Checkpointing → Memento (save pipeline state) + Event Sourcing
├─ Monitoring throughput → Observer + Decorator (metrics per stage)
├─ Conditional routing → Chain of Responsibility + Strategy (routing rule)
├─ Deduplication → Identity Map + Specification
└─ Backpressure → Producer-Consumer + Rate Limiter + Monitor
```

### "I'm building a rule engine or workflow engine"

```
Building a rule engine or workflow?
├─ Rules that compose → Specification + Composite (AND/OR/NOT)
│   └─ Rules selected at runtime → Strategy + Factory
├─ Ordered rule evaluation → Chain of Responsibility + Specification
├─ Workflow steps → Command + Template Method + State
│   ├─ Each step is a Command (executable, undoable)
│   ├─ Workflow skeleton is Template Method
│   └─ Workflow state is State Pattern
├─ Conditional branching → Strategy + Pattern Matching
├─ Parallel step execution → Future/Promise + Thread Pool
├─ Step retries → Retry + Command + Dead Letter Queue
├─ Audit of rule decisions → Observer + Event Sourcing
├─ Dynamic rule loading → Microkernel + Factory + Interpreter
├─ Rule storage and retrieval → Repository + Specification + Builder
└─ Testing rules → Specification (as test) + Test Data Builder + AAA
```

### "I'm integrating with external services or APIs"

```
Integrating with external services?
├─ Abstract the external API → Adapter + Facade + Repository (if data source)
│   └─ DI to inject the adapter (swap in tests with Test Double)
├─ Handle service failures → Circuit Breaker + Retry + Timeout + Fallback
│   └─ Combination: Proxy wraps CircuitBreaker wraps Retry wraps Adapter
├─ Cache responses → Proxy (caching proxy) + Memoization + Observer (TTL)
├─ Rate limiting outbound calls → Rate Limiter + Queue
├─ Async integration → Message Queue + Future/Promise + Observer
├─ Multiple providers (e.g., payment gateways) → Strategy + Abstract Factory
├─ Webhook handling → Observer + Command + Chain of Responsibility
├─ Data shape differences → DTO + Adapter + Data Mapper
├─ Auth to external service → Decorator + Strategy (auth type)
│   └─ Token refresh → Proxy (transparent refresh)
└─ Testing integration → Test Double (fake service) + DI + Builder (test data)
```

### "I'm dealing with performance problems"

```
Dealing with performance problems?
├─ Repeated expensive computations → Memoization + Proxy (transparent cache)
├─ Too many DB queries → Identity Map + Lazy Loading + Eager Loading strategy
├─ N+1 query problem → Repository (batch load) + Identity Map + Aggregate
├─ Memory pressure from many objects → Flyweight + Object Pool
├─ Thread creation overhead → Thread Pool + Object Pool
├─ Slow startup/initialization → Lazy Evaluation + Proxy (virtual proxy)
├─ Blocking I/O → Reactor + Future/Promise + Thread Pool
├─ CPU-bound parallelism → Thread Pool + Producer-Consumer + Actor Model
├─ High-throughput messaging → Message Queue + Producer-Consumer + Bulkhead
├─ Contended shared state → Immutability + Read-Write Lock + Actor Model
├─ Expensive object creation → Prototype (clone) + Object Pool
└─ Cache invalidation complexity → Observer (invalidate on change) + Proxy
```

### "I'm dealing with memory pressure"

```
Dealing with memory pressure?
├─ Many objects sharing common data → Flyweight + Factory (manages pool)
├─ Large objects loaded eagerly → Lazy Loading + Proxy (virtual proxy)
├─ Circular references → Weak references + Observer (careful registration)
├─ Large caches growing unbounded → Memoization (with LRU eviction) + Proxy
├─ Object creation overhead → Object Pool + Prototype
├─ Immutable data structures → Immutability + Flyweight (share sub-structures)
├─ Streaming large data → Iterator + Lazy Evaluation + Pipe and Filter
└─ Per-tenant isolation → Bulkhead + Object Pool per tenant
```

### "I'm building a notification or alerting system"

```
Building notifications or alerts?
├─ Fan-out to many recipients → Observer + Publish-Subscribe
├─ Different channels (email, SMS, push) → Strategy (per channel) + Abstract Factory
├─ User preferences per channel → Specification (preference rules) + Strategy
├─ Retry failed sends → Retry + Dead Letter Queue + Message Queue
├─ Deduplication → Specification + Identity Map (track sent)
├─ Batching → Producer-Consumer + Builder (batch assembly) + Template Method
├─ Rate limiting per user → Rate Limiter + Strategy (per-user limit)
├─ Template rendering → Template Method + Strategy (template engine)
├─ Audit of sent notifications → Observer + Event Sourcing
├─ Async delivery → Message Queue + Command + Future/Promise
└─ Testing → Test Double (fake sender) + Observer spy + Builder (test data)
```

### "I'm building a plugin or extension system"

```
Building a plugin or extension system?
├─ Core + interchangeable plugins → Microkernel + Factory (load plugins)
├─ Plugins register behavior → Observer + Chain of Responsibility
│   └─ Registration: Plugin calls register(self) at load time
├─ Plugins extend existing types → Decorator + OCP
├─ Plugins provide services → Abstract Factory + DI (inject plugin factories)
├─ Plugin discovery → Factory + Strategy (discovery mechanism)
│   ├─ File-based → Strategy reads directory
│   └─ Registry-based → Factory + Singleton registry
├─ Plugin isolation (failure) → Bulkhead + Proxy (catch plugin errors)
├─ Plugin ordering → Chain of Responsibility + Template Method
├─ Plugin configuration → Builder + Observer (config changes)
└─ Testing plugins → DI + Test Doubles (inject fake host) + AAA
```

### "I'm building a configuration system"

```
Building a configuration system?
├─ Multiple config sources → Chain of Responsibility (priority: env > file > default)
│   └─ Each source is a Handler in the chain
├─ Type-safe config → Builder (fluent) + Value Object (typed values)
│   └─ Validation → Guard Clause + Specification
├─ Runtime config changes → Observer (notify on change) + Strategy (reload)
├─ Environment-specific config → Abstract Factory (prod/staging/test factory)
├─ Secret management → Proxy (transparent secret fetch) + Decorator (cache)
├─ Config schema documentation → Builder (self-documenting) + Visitor
├─ Default values → Null Object (default config) + Builder
└─ Testing → Test Double (fake config) + Builder + DI
```

### "I'm implementing a caching layer"

```
Implementing caching?
├─ Transparent cache in front of expensive call → Proxy + Memoization
├─ Cache with TTL → Proxy + Observer (expiry events) + Strategy (eviction)
├─ Cache invalidation → Observer (invalidate on source change) + Event Bus
├─ Distributed cache → Proxy + Flyweight + Read-Write Lock
├─ Cache stampede prevention → Monitor + Future/Promise (deduplicate inflight)
├─ Write-through cache → Proxy + Observer + Unit of Work
├─ Multi-level cache (L1/L2/L3) → Chain of Responsibility (try each level)
├─ Selective caching → Specification (cache-eligibility rules) + Proxy
└─ Testing → Test Double (fake cache) + Observer spy + Builder (test scenarios)
```

### "I'm building an event-driven system"

```
Building an event-driven system?
├─ In-process events → Observer + Event Bus + Command (event handlers)
├─ Cross-service events → Publish-Subscribe + Message Queue + DTO (event shape)
├─ Event ordering guarantees → Event Sourcing + Message Queue (ordered)
├─ Event schema evolution → Adapter (translate old → new) + Strategy
├─ Event replay → Event Sourcing + Repository + Observer
├─ Projections from events → CQRS + Observer + Template Method
├─ Saga coordination → Saga + Command + Observer + Dead Letter Queue
├─ At-least-once delivery → Retry + Idempotency (Specification or Identity Map)
├─ Event sourcing + snapshotting → Event Sourcing + Memento (snapshots)
└─ Testing → Test Double (fake bus) + Observer spy + Builder (test events) + AAA
```

### "I'm implementing authentication and authorization"

```
Implementing auth/authz?
├─ Multiple authentication methods → Strategy (per method: JWT, OAuth, API key)
│   └─ Select at runtime → Factory + Chain of Responsibility
├─ Request pipeline auth → Chain of Responsibility + Decorator + Proxy
├─ Permission checking → Specification (permission rules) + Proxy + Guard Clause
├─ Role-based access → Strategy (per role) + Specification + Decorator
├─ Resource-level permissions → Specification + Visitor (check per resource type)
├─ Token refresh → Proxy (intercept expired tokens, refresh transparently)
├─ Session management → State Pattern (authenticated/anonymous/expired)
├─ Audit logging of auth events → Observer + Event Sourcing + Decorator
├─ Multi-tenant isolation → Strategy (per-tenant resolver) + Bulkhead
└─ Testing → Test Double (fake identity) + Builder (test users/roles) + AAA
```

### "I'm building a reporting or analytics system"

```
Building reporting/analytics?
├─ Complex queries → Specification (query composition) + Repository + CQRS
│   └─ Read model separate from write → CQRS + separate Repository
├─ Report templates → Template Method + Strategy (data source)
├─ Multiple output formats → Strategy (PDF, CSV, JSON) + Builder (per format)
├─ Data aggregation → Visitor + Composite (hierarchical totals)
├─ Scheduled reports → Command + Scheduler + Observer (on completion)
├─ Real-time dashboard → CQRS + Observer + Pub-Sub + Flyweight (shared data)
├─ Cached expensive computations → Memoization + Proxy + Observer (invalidate)
├─ Historical data → Event Sourcing + CQRS + Repository (time-sliced)
└─ Testing → Test Data Builder + Repository stub + Strategy (test formatter)
```

### "I'm dealing with vendor lock-in"

```
Dealing with third-party vendor lock-in?
├─ Wrap the vendor API → Adapter + Facade (your own interface)
│   └─ DIP: depend on your abstraction, not theirs
├─ Support multiple vendors → Abstract Factory + Strategy (per vendor)
│   └─ Adapter per vendor, shared interface
├─ Easy vendor replacement → Repository (data access) + DI (inject adapter)
├─ Test without the vendor → Test Double (fake adapter) + DI
├─ Incremental vendor migration → Strangler Fig + Adapter (both old/new)
├─ Vendor-specific data formats → Data Mapper + DTO (translate at boundary)
└─ Monitor vendor health → Proxy (intercept calls) + Circuit Breaker + Observer
```

### "I'm designing a domain model"

```
Designing a domain model?
├─ Core domain concepts → Value Object (immutable, value equality)
│   └─ Examples: Money, Email, PhoneNumber, Address, DateRange
├─ Entities with identity → Aggregate root with Guard Clause
├─ Invariant enforcement → Guard Clause + Fail-Fast in constructors
├─ Grouping related entities → Aggregate + Repository per aggregate
├─ Business rule expression → Specification (composable, testable)
├─ Complex state transitions → State Pattern + Observer (domain events)
├─ Type hierarchies → LSP + Factory Method + Strategy (behavior variation)
├─ Avoiding primitive obsession → Value Object (wrap primitives with meaning)
├─ Domain events → Observer + Event Sourcing + Command
└─ Domain service vs entity → Service Layer (stateless domain operations)
```

### "I'm implementing business rules or policies"

```
Implementing business rules?
├─ Express rules as objects → Specification Pattern
│   └─ Compose rules → Composite (AND, OR, NOT of Specifications)
├─ Rules that vary → Strategy (different rule implementations)
├─ Rules with priority → Chain of Responsibility (ordered rule evaluation)
├─ Rules that enable/disable → Observer (react to config changes) + Strategy
├─ Rules per customer/tenant → Abstract Factory (per-tenant rule set)
├─ Rules with side effects → Command (rule execution as Command)
├─ Rules for validation → Guard Clause + Specification + Fail-Fast
├─ Rules that query data → Repository + Specification (data-driven rules)
├─ Document rules as tests → Specification + Given-When-Then
└─ Dynamic rules → Interpreter + Repository (store rule expressions)
```

### "I'm adding logging, monitoring, or observability"

```
Adding observability?
├─ Add logging to existing code → Decorator + Proxy (non-invasive)
├─ Structured log output → Builder (log entry) + Strategy (format: JSON, text)
├─ Metrics collection → Observer + Decorator (count/time each operation)
├─ Distributed tracing → Decorator + Proxy (inject trace context)
│   └─ Cross-service → Sidecar + Decorator
├─ Alerting on thresholds → Observer + Specification (threshold rules)
├─ Health checks → Command (health check commands) + Strategy (per service)
├─ Audit logging → Observer + Event Sourcing (immutable audit trail)
├─ Performance profiling → Proxy + Decorator + Memoization (baseline)
└─ Testing observability → Test Double (spy on observer) + Observer + AAA
```

### "I'm working with files, streams, or I/O"

```
Working with files, streams, I/O?
├─ Stream transformation → Pipe and Filter + Iterator + Lazy Evaluation
├─ Different file formats → Strategy (parser per format) + Abstract Factory
├─ Reading large files → Iterator + Lazy Evaluation + Producer-Consumer
├─ Writing to multiple outputs → Observer + Strategy (per output)
├─ Buffered I/O → Decorator (add buffering) + Proxy
├─ Retry on I/O errors → Retry + Circuit Breaker + Fallback
├─ File format conversion → Adapter (between format models) + Data Mapper
├─ Watching for file changes → Observer + Reactor (event loop)
├─ Compression/encryption → Decorator (stacked transforms) + Strategy
├─ Resource cleanup → Template Method (open/process/close skeleton)
└─ Testing file I/O → Test Double (fake filesystem) + DI + Builder (test files)
```

### "I'm implementing a scheduler or job queue"

```
Building a scheduler or job queue?
├─ Job representation → Command (each job is a Command object)
├─ Job scheduling → Strategy (cron, interval, one-shot)
├─ Worker pool → Thread Pool + Producer-Consumer
├─ Job retries → Retry + Command + Dead Letter Queue
├─ Job prioritization → Chain of Responsibility (priority queues)
├─ Job deduplication → Identity Map + Specification
├─ Distributed jobs → Message Queue + Actor Model + Saga (multi-step jobs)
├─ Job status tracking → Observer + State Pattern (pending/running/done/failed)
├─ Job result handling → Future/Promise + Observer + Result Type
├─ Job cancellation → Command (cancel command) + Future/Promise (cancel token)
└─ Testing → Test Double (fake scheduler) + Command + AAA
```

### "I need code to be testable"

```
Making code testable?
├─ Every dependency must be injectable → DI + DIP + Factory
├─ Public methods must have single clear responsibility → SRP
├─ No hidden state or global variables → Immutability + DI
├─ Business rules must be extractable → Specification + Strategy
├─ External calls must be swappable → Adapter + Repository + DI
├─ Side effects must be isolatable → Hexagonal Architecture + Adapter
├─ Complex objects must be constructable in tests → Builder + Test Data Builder
├─ Behavior must be verifiable → Observer (spy on events) + Command (verify calls)
├─ State transitions must be testable → State Pattern + AAA per transition
└─ Error paths must be reachable → Guard Clause + Result Type + Test Doubles
```

### "I'm working with third-party libraries or frameworks"

```
Working with third-party code?
├─ Wrap the library → Adapter (own interface) + Facade (simplified API)
│   └─ DIP: your code depends on your interface, not the library's
├─ The library uses callbacks/events → Adapter + Observer (convert to events)
├─ Extend library behavior → Decorator + OCP
├─ The library has a framework pattern → Template Method (fill in the blanks)
├─ Multiple library versions → Adapter (version-specific adapters)
├─ Test without the library → Test Double + DI (inject your adapter)
├─ The library is slow → Proxy + Memoization + Lazy Evaluation
└─ The library might be replaced → Repository/Adapter abstraction + DI
```

### "I'm building concurrent or parallel code"

```
Building concurrent/parallel code?
├─ CPU-bound parallelism → Thread Pool + Future/Promise + Producer-Consumer
├─ I/O-bound concurrency → Reactor + Future/Promise + Actor Model
├─ Shared mutable state → Monitor + Read-Write Lock + Immutability
│   └─ Best: eliminate shared state → Actor Model + Immutability
├─ Work distribution → Producer-Consumer + Thread Pool + Bulkhead
├─ Async coordination → Future/Promise + Observer + Monad (async chains)
├─ Message-passing concurrency → Actor Model + Message Queue
├─ Rate controlling concurrent work → Rate Limiter + Bulkhead + Thread Pool
├─ Parallel aggregation → Thread Pool + Future/Promise + Collector pattern
├─ Concurrent data structures → Read-Write Lock + Immutability + Monitor
└─ Testing concurrent code → Test Double (controllable timing) + Observer + AAA
```

### "I'm modeling a complex domain with interactions"

```
Modeling complex domain interactions?
├─ Many objects interact → Mediator (centralize communication)
│   └─ OR: Event Bus (decentralized with events)
├─ Rich domain logic → Aggregate + Specification + Value Object + Guard Clause
├─ Cross-cutting domain rules → Specification + Visitor
├─ Domain state machine → State Pattern + Observer (emit domain events)
├─ Domain events → Observer + Event Bus + Event Sourcing
├─ Complex queries over domain → Specification + Repository + CQRS
├─ Domain invariant enforcement → Aggregate (root enforces) + Guard Clause
├─ Extensible domain actions → Command + Strategy + Visitor
├─ Domain model + persistence → Repository + Data Mapper + Unit of Work
└─ Domain model + UI → MVC/MVVM + DTO (don't expose domain to view)
```

### "I'm building a search or discovery system"

```
Building search or discovery?
├─ Composable query/filter criteria → Specification + Composite (AND/OR/NOT)
│   └─ Each facet is a Specification; compose at query time
├─ Multiple search backends (Elasticsearch, DB, in-memory) → Strategy + Adapter
│   └─ Abstract factory to switch backend per environment
├─ Query construction → Builder (fluent query builder) + Value Object (query terms)
├─ Pagination and cursor-based iteration → Iterator + Repository + Specification
├─ Search result ranking/sorting → Strategy (different ranking algorithms)
├─ Query autocomplete/suggestions → Memoization + Lazy Evaluation + Proxy (cache)
├─ Faceted search → Visitor (count per facet) + Composite + Repository
├─ Full-text search indexing → Observer (index on entity save) + Command
├─ Async indexing → Message Queue + Command (index job) + Observer
├─ Search result shaping → DTO + Builder (per result type) + Facade
└─ Testing → Specification (assert results) + Test Data Builder + Repository stub
```

### "I'm building a game or simulation loop"

```
Building a game or simulation?
├─ Game loop (update/render cycle) → Template Method (fixed skeleton)
│   └─ Each system is a Strategy inside the loop
├─ Game entities/components → Composite (scene graph) + Iterator (all entities)
├─ Entity behavior variation → Strategy (AI behavior) + State (entity state)
│   └─ Entity FSM: Idle → Patrol → Chase → Attack → Dead
├─ User input handling → Command (every action is a Command)
│   └─ Input replay and undo → Command + Memento
├─ Physics / collision events → Observer + Event Bus (decouple systems)
├─ Asset management → Flyweight (share sprites/textures) + Object Pool (bullets)
├─ Save/load state → Memento + Prototype (clone game state)
├─ Spawning entities → Factory + Object Pool (reuse pooled instances)
├─ Game rules/scoring → Specification + Observer + Event Sourcing (replay)
├─ Multiplayer sync → Actor Model + Message Queue + Event Sourcing
├─ AI decision trees → Strategy + Composite + Chain of Responsibility
└─ Modding support → Microkernel + Factory + Observer (event hooks for mods)
```

### "I'm implementing feature flags or A/B testing"

```
Implementing feature flags or experiments?
├─ Toggle features on/off → Strategy (enabled/disabled implementation)
│   └─ NullObject as disabled strategy; real impl as enabled
├─ Feature flag resolution → Chain of Responsibility (user → org → global)
│   └─ Each resolver is a Handler: user-override → experiment → org config → default
├─ Flag evaluation rules → Specification (percentage rollout, user segment rules)
├─ Flag config loading → Builder + Observer (hot-reload without restart)
├─ Experiment assignment → Strategy (hash-based, random, targeted)
├─ Tracking experiment exposure → Observer + Event Bus + Event Sourcing
├─ Gradual rollout → Strategy + Proxy (intercept call, apply rollout logic)
├─ Emergency kill switch → Circuit Breaker (treat bad flag as circuit)
├─ Flag dependencies → Composite (flag A requires flag B)
├─ Testing with flags → Test Double (inject FlagService) + DI + Builder
└─ Audit of flag changes → Observer + Event Sourcing (who changed what when)
```

### "I'm building a subscription or billing system"

```
Building subscriptions or billing?
├─ Subscription plans with different features → Strategy (plan = strategy)
│   └─ Abstract Factory creates plan-specific resources
├─ Billing events (charge, refund, invoice) → Command + Event Sourcing
├─ Proration calculations → Value Object (Money) + Strategy (proration algorithm)
├─ Dunning (retrying failed payments) → Retry + Dead Letter Queue + State
│   └─ State: Active → PastDue → Suspended → Cancelled
├─ Metered billing (usage tracking) → Observer + Decorator (wrap billable ops)
│   └─ Usage events → Message Queue + Command (aggregate usage async)
├─ External payment processor → Adapter + Facade + Circuit Breaker
├─ Invoice generation → Builder (invoice builder) + Template Method + Strategy
├─ Trial periods → State Pattern (Trial → Active → Expired)
├─ Discount/coupon application → Decorator + Specification (eligibility rules)
├─ Multi-currency → Value Object (Money with currency) + Strategy (FX rate source)
└─ Webhooks from payment processor → Observer + Command + Retry + Dead Letter Queue
```

### "I'm implementing soft delete, archiving, or tombstoning"

```
Implementing soft delete or archiving?
├─ Soft delete flag on entities → Specification (active_only filter in Repository)
│   └─ Repository always applies spec: where(is_deleted=False)
├─ Restore deleted records → Command (RestoreCommand) + Memento (original state)
├─ Archived vs active queries → Specification + Repository (two query paths)
├─ Cascade soft-delete to children → Visitor (traverse + mark) + Unit of Work
├─ Audit who deleted what when → Observer + Event Sourcing + Decorator
├─ Hard delete after retention period → Command (PurgeCommand) + Scheduler
│   └─ Purge is a Saga (delete data → confirm → emit event)
├─ Prevent accidental deletion → Guard Clause + Specification (deletion rules)
└─ Testing → Specification (assert filtered) + Test Data Builder + Repository stub
```

### "I'm building internationalization (i18n) or localization"

```
Building i18n/localization?
├─ Locale-specific behavior → Strategy (per locale: formatting, sorting)
├─ Translation loading → Abstract Factory (per locale) + Flyweight (share strings)
├─ Locale resolution → Chain of Responsibility (user → org → browser → default)
├─ Date/number formatting → Strategy (locale-specific formatter)
├─ Locale-aware sorting → Strategy (locale-specific comparator)
├─ Runtime locale switching → Observer (notify components on locale change)
├─ Missing translation fallback → Chain of Responsibility + Null Object
│   └─ Try: user locale → base locale → fallback string
├─ Pluralization rules → Strategy (per language) + Interpreter (CLDR rules)
├─ RTL layout switching → Decorator (RTL wrapper) + Strategy
└─ Testing → Test Double (fake translator) + Builder (multilingual test data)
```

### "I'm optimizing database interaction"

```
Optimizing database interaction?
├─ Eliminate N+1 queries → Repository (batch fetch) + Identity Map
├─ Avoid loading unused columns → Specification (projection spec) + Repository
├─ Cache frequently read data → Proxy (caching proxy) + Memoization + Observer
├─ Write batching → Unit of Work (accumulate, batch commit) + Command
├─ Read replicas → Strategy (primary vs replica selection) + Repository
├─ Query result pagination → Iterator + Specification + Repository + DTO
├─ Full-text search offload → Adapter (search engine) + Observer (keep in sync)
├─ Connection management → Object Pool + Monitor (thread-safe pool)
├─ Schema migration safety → Strangler Fig (dual-write) + Adapter
├─ Optimistic locking → Guard Clause (check version) + Unit of Work
└─ Testing → Repository (in-memory fake) + Identity Map + Test Data Builder
```

### "I'm building an AI agent or LLM-based system"

```
Building an AI agent or LLM system?
├─ Agent reasoning loop → Template Method (perceive → reason → act skeleton)
│   └─ Each phase is a Strategy (pluggable perception, reasoning, action)
├─ Tool / function use → Command (each tool is a Command)
│   └─ Register tools → Factory + Registry + Chain of Responsibility
├─ Memory / context management → Memento (save/restore context windows)
│   └─ Long-term memory → Repository + Specification (retrieve by relevance)
├─ Multiple LLM backends → Abstract Factory + Adapter (per provider)
│   └─ Swap models without changing agent logic
├─ Prompt construction → Builder (fluent prompt builder)
│   └─ Prompt templates → Template Method
├─ Streaming responses → Iterator + Observer + Reactor (async streaming)
├─ Caching LLM responses → Memoization + Proxy (transparent cache by prompt hash)
├─ Retry on rate limits → Retry + Rate Limiter + Circuit Breaker
├─ Multi-agent coordination → Mediator + Message Queue + Actor Model
│   └─ Agents are actors; mediator routes tasks
├─ Evaluation / scoring → Strategy (per metric) + Observer (log results)
└─ Testing → Test Double (fake LLM) + Builder (test prompts) + Strategy (eval)
```

### "I'm implementing a file upload or media processing system"

```
Building file upload or media processing?
├─ Upload validation → Guard Clause + Specification (MIME type, size, virus scan)
├─ Multi-stage processing → Pipe and Filter + Chain of Responsibility
│   └─ Stages: validate → scan → resize → transcode → store → notify
├─ Async processing → Message Queue + Command (each stage) + Future/Promise
├─ Progress tracking → Observer + State Pattern (Pending → Processing → Done)
├─ Multiple storage backends → Strategy + Adapter (local, S3, GCS, Azure)
├─ CDN integration → Proxy (serve via CDN) + Decorator (add CDN URL transform)
├─ Deduplication → Identity Map (hash → stored URL) + Specification
├─ Format conversion → Strategy (converter per format pair) + Pipe and Filter
├─ Error handling → Result Type + Dead Letter Queue (failed files for review)
├─ Retry on transient failures → Retry + Circuit Breaker (if storage is down)
├─ Access control → Proxy (auth check before serving) + Guard Clause
└─ Testing → Test Double (fake storage) + Builder (test files) + Strategy
```

### "I'm building a content management system"

```
Building a CMS?
├─ Content hierarchy (pages, sections, widgets) → Composite (content tree)
│   └─ Iterator to traverse + Visitor for operations on nodes
├─ Content types with variations → Abstract Factory (per content type)
│   └─ Factory Method to instantiate correct renderer per type
├─ Content versioning → Event Sourcing + Memento (version snapshots)
├─ Draft/published states → State Pattern (Draft → Review → Published → Archived)
├─ Templating → Template Method (base layout + overrideable slots)
│   └─ Strategy for template engine (Jinja, Mustache, etc.)
├─ Scheduled publishing → Command (PublishCommand) + Scheduler + Observer
├─ Permission model → Specification + Proxy (gate content access)
├─ Search indexing → Observer (index on publish) + Command + Message Queue
├─ Multi-site / multi-tenant → Abstract Factory (per site) + Strategy
├─ Media assets → Flyweight (share assets across pages) + Repository
└─ Testing → Composite (test tree) + Test Data Builder + State verification
```

### "I'm implementing OAuth2, SSO, or federated identity"

```
Implementing OAuth2 or SSO?
├─ Multiple OAuth providers → Strategy (per provider: Google, GitHub, SAML)
│   └─ Abstract Factory to instantiate correct provider flow
├─ Auth flow state machine → State Pattern (init → redirect → callback → done)
├─ Token lifecycle → State Pattern + Observer (token expiry events)
│   └─ Token refresh → Proxy (intercept expired token, refresh transparently)
├─ Session management → Memento (save/restore session state)
├─ Authorization code flow → Command (each step) + Chain of Responsibility
├─ Scope/permission mapping → Specification (scope → permission rules)
├─ User provisioning on first login → Saga (create user → assign roles → log)
├─ Token introspection / validation → Proxy + Guard Clause + Cache (Memoization)
├─ Logout / token revocation → Observer (notify all active sessions) + Command
└─ Testing → Test Double (fake provider) + State verification + Builder (test tokens)
```

### "I'm building a graph or network traversal system"

```
Building graph or network traversal?
├─ Graph structure → Composite (nodes with edges) + Iterator (graph traversal)
├─ Multiple traversal strategies → Strategy (BFS, DFS, Dijkstra, A*)
├─ Visiting each node once → Visitor + Iterator + Identity Map (track visited)
├─ Graph modification operations → Command + Memento (undo graph edits)
├─ Cycle detection → Specification (detect cycle) + Iterator + Guard Clause
├─ Parallel graph traversal → Thread Pool + Future/Promise + Actor Model
├─ Graph serialization → Visitor (serialize) + Builder (deserialize)
├─ Lazy graph loading → Lazy Loading + Proxy (load neighbors on demand)
├─ Graph analytics/metrics → Visitor (compute per node) + Flyweight (shared context)
└─ Testing → Composite (test graph) + Visitor + Test Data Builder
```

### "I'm implementing an audit or compliance system"

```
Building an audit or compliance system?
├─ Capture all state changes → Event Sourcing (append-only event log)
│   └─ Observer to intercept changes at service layer + Decorator
├─ Structured audit records → Builder (audit entry) + Value Object (typed fields)
├─ Immutable audit trail → Immutability + Event Sourcing (events never deleted)
├─ Who did what when → Decorator (inject actor identity) + Observer
├─ Compliance rules → Specification (composable rules) + Chain of Responsibility
├─ Report generation → CQRS (read side for compliance queries) + Repository
│   └─ Template Method + Strategy for different compliance report formats
├─ Real-time alerts → Observer + Specification (alert thresholds) + Pub-Sub
├─ Data retention policies → Specification + Scheduler + Command (purge)
├─ Access log → Proxy (log every access) + Observer + Event Bus
└─ Testing → Event Sourcing replay + Specification (assert compliance) + AAA
```

### "I'm building a real-time collaboration system"

```
Building real-time collaboration (e.g., shared document editing)?
├─ Conflict-free concurrent edits → Command (operations) + Event Sourcing
│   └─ Operational Transformation or CRDT implemented as Command
├─ Connection management → Reactor + Actor Model (per connected client)
├─ Broadcasting changes → Observer + Publish-Subscribe (per document topic)
├─ Presence awareness (who is online) → Observer + Flyweight (presence data)
├─ Cursor / selection sync → Observer + Value Object (CursorPosition)
├─ Permission per document → Specification + Proxy (gate write access)
├─ Optimistic local updates → Memento (local undo if server rejects)
├─ Offline sync → Event Sourcing (local queue) + Saga (sync on reconnect)
├─ History and replay → Event Sourcing + Iterator + CQRS
└─ Testing → Actor Model (test actors) + Event Sourcing (replay) + Observer spy
```

### "I'm working with an API that has breaking changes"

```
Dealing with API versioning or breaking changes?
├─ Support multiple API versions → Adapter (v1/v2 adapters) + Facade
│   └─ Route by version: Chain of Responsibility or Strategy
├─ Gradual deprecation → Strangler Fig + Proxy (redirect v1 → v2)
├─ Backward-compatible extension → Decorator (add new fields without breaking)
├─ Schema evolution → Adapter (translate old payload → new model) + DTO
├─ Consumer-driven contracts → Specification (contract = spec) + Test Double
├─ Versioned DTOs → Builder (per version) + Data Mapper (transform)
├─ API Gateway versioning → API Gateway + Strategy (route to versioned handler)
├─ Sunset old endpoints → Observer (log deprecated usage) + Guard Clause (warn)
└─ Testing → Adapter (test each version) + AAA + Test Data Builder
```

### "I'm handling bulk operations or batch processing"

```
Handling bulk operations or batch processing?
├─ Process items in parallel → Thread Pool + Future/Promise + Producer-Consumer
├─ Transactional batch → Unit of Work (commit all or rollback all)
├─ Partial failure handling → Result Type (per item) + Dead Letter Queue (failed)
├─ Large dataset streaming → Iterator + Lazy Evaluation + Pipe and Filter
├─ Batch job definition → Command (each job) + Builder (job configuration)
├─ Progress reporting → Observer + State Pattern (job lifecycle)
├─ Rate limiting batch → Rate Limiter + Bulkhead
├─ Idempotent operations → Identity Map (track processed IDs) + Guard Clause
├─ Retry failed items → Retry + Command + Dead Letter Queue
├─ Batch data validation → Specification (per-record) + Guard Clause (batch-level)
└─ Testing → Test Data Builder + Command + Observer spy + AAA
```

### "I'm implementing pagination, sorting, and filtering"

```
Implementing pagination, sorting, filtering?
├─ Filter criteria → Specification + Composite (AND/OR/NOT)
│   └─ Each filter param becomes a Specification object
├─ Sorting → Strategy (per sort field/direction) + Builder (sort spec)
├─ Cursor-based pagination → Iterator + Value Object (cursor = opaque token)
├─ Offset-based pagination → Repository + Specification + DTO (page metadata)
├─ Total count (avoid N+2) → Repository.count(spec) cached with Memoization
├─ Default sort/filter → Null Object (default Specification) + Chain of Responsibility
├─ Sorting/filter persistence (remember user prefs) → Memento + Repository
├─ Faceted counts → Visitor (count per facet) + Repository
├─ URL-to-Specification mapping → Interpreter (parse query string) + Builder
└─ Testing → Specification + Test Data Builder + Repository stub + AAA
```

### "I'm building a webhook delivery or integration system"

```
Building webhook delivery?
├─ Webhook registration → Repository (webhook configs) + Builder (webhook object)
├─ Event routing → Publish-Subscribe + Observer + Specification (filter events)
│   └─ Each webhook = a Subscriber with a Specification of events it cares about
├─ Delivery with retries → Retry + Dead Letter Queue + Command (delivery task)
│   └─ Exponential backoff: 1min → 5min → 30min → 2h → 24h
├─ Circuit breaker per endpoint → Circuit Breaker (per webhook URL)
├─ Delivery tracking → Event Sourcing (log every attempt) + State
│   └─ State: Pending → Delivering → Delivered / Failed / Dead
├─ Payload signing → Decorator (HMAC sign before send) + Strategy (hash algo)
├─ Fan-out delivery → Message Queue + Thread Pool (parallel delivery)
├─ Webhook testing → Command (send test event) + Observer (log response)
└─ Testing → Test Double (fake HTTP client) + Observer spy + Retry verification
```

### "I'm building a GraphQL API"

```
Building a GraphQL API?
├─ Resolver composition → Composite (nested resolvers form a tree) + Factory
├─ N+1 query problem → Repository (DataLoader batch) + Identity Map + Lazy Loading
├─ Authorization per field → Proxy (per-field auth) + Specification + Guard Clause
├─ Input validation → Guard Clause + Value Object (typed scalars) + Fail-Fast
├─ Schema-driven response → DTO + Builder (build response shape from schema)
├─ Mutation handling → Command (each mutation is a Command) + Service Layer
├─ Query complexity limiting → Specification (complexity rule) + Guard Clause
├─ Caching resolver results → Memoization + Proxy (cache per argument hash)
├─ Subscription support → Observer + Pub-Sub + Reactor (async streaming)
├─ Error formatting → Exception Hierarchy + Result Type + Null Object
├─ Schema stitching/federation → Adapter (per service schema) + Facade
└─ Testing → Test Double (fake resolvers) + Builder (test queries) + AAA
```

### "I'm implementing data validation and sanitization"

```
Implementing data validation and sanitization?
├─ Validate at every public boundary → Guard Clause + Fail-Fast
│   └─ Never trust input — validate in every public/protected method
├─ Composable validation rules → Specification + Composite (AND/OR/NOT rules)
│   └─ Each rule is a Specification: required, min_length, max_value, pattern
├─ Type-safe validated values → Value Object (validate in constructor)
│   └─ Email, PhoneNumber, URL, Money — wraps primitives, enforces invariants
├─ Sanitization pipeline → Pipe and Filter (strip → normalize → validate)
├─ Async validation (DB uniqueness check) → Future/Promise + Specification
├─ Validation error collection → Result Type (collect all errors, not just first)
│   └─ Chain: Monad collecting multiple Err values before failing
├─ Context-sensitive rules → Strategy (rules vary by user type, locale)
├─ Cross-field validation → Specification (rule over entire object)
├─ Schema validation → Interpreter (parse schema) + Specification
└─ Testing → Specification (assert valid/invalid) + Test Data Builder + AAA
```

### "I'm building a payment processing system"

```
Building payment processing?
├─ Multiple payment providers → Strategy + Abstract Factory (per provider)
│   └─ Adapter wraps each provider's SDK to a common PaymentGateway interface
├─ Payment flow state → State Pattern (initiated → pending → captured → failed → refunded)
├─ Multi-step payment → Saga (authorize → capture → settle; compensating: void/refund)
├─ Provider failures → Circuit Breaker + Retry (with jitter) + Fallback (provider B)
├─ Idempotency → Identity Map (idempotency key → result) + Guard Clause
├─ Currency/amount safety → Value Object (Money = amount + currency; no float math)
├─ PCI compliance boundary → Hexagonal (payment is a port) + Adapter + Sidecar
├─ Fraud detection → Chain of Responsibility + Specification (fraud rules)
│   └─ Rules applied in order; any failure blocks transaction
├─ Webhook from provider → Observer + Command + Retry + Dead Letter Queue
├─ Reconciliation → CQRS (event log vs ledger) + Repository + Specification
└─ Testing → Test Double (fake gateway) + Saga (test compensations) + Builder
```

### "I'm building a booking or reservation system"

```
Building a booking or reservation system?
├─ Resource availability → Specification (date range, capacity, conflict check)
│   └─ Specification: is_available(resource, start, end)
├─ Reservation lifecycle → State Pattern (Pending → Confirmed → Checked-In → Completed)
├─ Concurrent booking race → Monitor + Optimistic Lock (Guard Clause on version)
│   └─ OR: Actor Model (resource actor serializes bookings)
├─ Multi-resource booking → Saga (reserve A → reserve B → confirm; compensate on fail)
├─ Pricing rules → Strategy (per resource type, time slot, season)
│   └─ Decorator stack: BasePrice + PeakSurcharge + LoyaltyDiscount
├─ Waitlist → Observer (notify on cancellation) + Queue (FIFO waitlist)
├─ Calendar/schedule → Composite (hierarchical: venue → room → slot)
├─ Hold/release timeout → Command (hold) + Scheduler (auto-release) + Observer
├─ Cancellation policy → Strategy (per booking type) + Specification (eligible)
├─ Search/discovery → Specification + Repository + Iterator (availability windows)
└─ Testing → Test Data Builder + State + Specification + Saga (compensation paths)
```

### "I'm building a recommendation or personalization engine"

```
Building recommendations or personalization?
├─ Recommendation algorithm → Strategy (collaborative filtering, content-based, hybrid)
│   └─ Abstract Factory to select algorithm per user type or context
├─ User preference model → Aggregate (user profile root) + Observer (update on actions)
├─ Action tracking → Observer + Event Bus + Event Sourcing (click, view, purchase)
├─ Real-time vs batch → Strategy (real-time: Reactor; batch: Thread Pool + Producer-Consumer)
├─ Filtering out seen items → Specification + Identity Map (track shown items)
├─ A/B test different algorithms → Strategy + Feature Flag + Observer (track results)
├─ Result caching → Memoization + Proxy (cache by user_id + context)
├─ Fallback (cold start / no data) → Null Object (return popular items) + Strategy
├─ Diversity enforcement → Specification + Decorator (ensure category spread)
├─ Privacy / data minimization → Value Object (anonymized ID) + Specification
└─ Testing → Test Data Builder + Strategy (deterministic test algorithm) + Observer spy
```

### "I'm implementing distributed locking or coordination"

```
Implementing distributed locking or coordination?
├─ Mutual exclusion across processes → Proxy (distributed lock as proxy)
│   └─ Lock backed by Redis, ZooKeeper, DB — implementation behind Adapter
├─ Lock acquisition with timeout → Monitor + Future/Promise + Timeout
├─ Prevent lock starvation → Read-Write Lock + Strategy (fairness policy)
├─ Leader election → Actor Model + Observer (react to leader change)
├─ Fencing tokens → Value Object (FencingToken = monotonic counter + TTL)
│   └─ Guard Clause: reject operations with stale tokens
├─ Optimistic locking (no distributed lock) → Guard Clause (check version) + Retry
├─ Semaphore / quota → Monitor + Bulkhead + Rate Limiter
├─ Lock-free coordination → Immutability + Actor Model (no shared state)
├─ Distributed barrier → Future/Promise + Observer (all parties signal arrival)
└─ Testing → Test Double (fake lock) + Monitor (controllable) + Observer + AAA
```

### "I'm implementing graceful shutdown and startup lifecycle"

```
Implementing graceful startup/shutdown?
├─ Ordered startup → Chain of Responsibility (each component starts in order)
│   └─ Template Method (init hooks: pre-start → start → post-start)
├─ Dependency-aware startup → Composite + Observer (notify dependents when ready)
├─ Health/readiness probes → Strategy (per health check type) + Command
├─ Graceful shutdown signal → Observer (broadcast SIGTERM) + Command (each component)
│   └─ Command: drain → stop accepting → finish in-flight → release resources
├─ In-flight request draining → Monitor + Counter + Future/Promise (await zero)
├─ Connection cleanup → Template Method (acquire → use → release skeleton)
├─ Config hot-reload → Observer (detect file change) + Strategy (reload without restart)
├─ Startup idempotency → Guard Clause (check if already running) + State
│   └─ State: Stopped → Starting → Running → Stopping → Stopped
├─ Retry startup on failure → Retry + Circuit Breaker + Observer (alert on fail)
└─ Testing → Observer spy + State verification + Command + AAA
```

### "I'm implementing schema migration or data migration"

```
Implementing schema or data migration?
├─ Incremental migration → Strangler Fig (dual-write old + new schema)
│   └─ Proxy routes reads to old, writes to both; cut over when stable
├─ Versioned migrations → Command (each migration is a Command)
│   └─ Ordered by version; Chain of Responsibility applies pending ones
├─ Idempotent migrations → Guard Clause (check if already applied) + Identity Map
├─ Schema evolution without downtime → Adapter (new code reads both schemas)
├─ Data backfill → Producer-Consumer + Thread Pool + Command (backfill job)
│   └─ Retry + Dead Letter Queue for failed rows
├─ Rollback support → Memento (save pre-migration state) + Command (undo)
├─ Validation after migration → Specification (assert data integrity) + Repository
├─ Progress tracking → Observer + State (pending/running/done/failed)
├─ Big table migration (no locks) → Iterator (batch by ID range) + Unit of Work
└─ Testing → Repository (before/after) + Specification (assert correctness) + AAA
```

### "I'm building a SaaS onboarding or setup wizard"

```
Building SaaS onboarding or multi-step wizard?
├─ Step sequence → State Pattern (step1 → step2 → step3 → complete)
│   └─ Each step is a Command (validate → save → advance state)
├─ Step validation → Guard Clause + Specification (per-step requirements)
├─ Allow back navigation → Memento (save state at each step for back button)
├─ Skip optional steps → State + Strategy (conditional step ordering)
├─ Async setup tasks → Saga (provision resources in parallel steps)
│   └─ Command per task: create_workspace → invite_team → seed_data
├─ Progress persistence → Repository (save wizard state) + Unit of Work
├─ Abandonment handling → Observer (detect timeout/abandonment) + Command (cleanup)
├─ Different flows per plan → Abstract Factory + Strategy (flow per account type)
├─ Completion rewards/hooks → Observer (emit OnboardingComplete) + Command
└─ Testing → State + Test Data Builder + Saga (test all completion paths) + AAA
```

### "I'm building a social graph or relationship system"

```
Building a social graph or relationship system?
├─ Graph structure → Composite (user nodes + relationship edges) + Iterator
├─ Relationship types (follow, friend, block) → State + Strategy (bidirectional vs asymmetric)
├─ Graph traversal (friends of friends) → Iterator + Strategy (BFS, DFS)
│   └─ Identity Map to avoid revisiting same node
├─ Privacy/visibility → Specification (visibility rules) + Proxy (gate traversal)
├─ Mutual connection detection → Visitor + Specification (intersection logic)
├─ Feed generation → Observer (on new post) + CQRS (fan-out write model)
│   └─ Pub-Sub (broadcast to followers) or Pull (query on load)
├─ Blocking → Guard Clause + Specification (block check before interaction)
├─ Recommendation (who to follow) → Strategy + Repository + Memoization
├─ Notification on relationship event → Observer + Strategy (per channel)
└─ Testing → Composite (test graph) + Test Data Builder + Specification + AAA
```

### "I'm implementing an API SDK or client library"

```
Building an API SDK or client library?
├─ Fluent, discoverable interface → Builder + Facade
│   └─ Client.for_resource(id).with_auth(token).get()
├─ Auth handling → Strategy (API key, OAuth, Basic) + Decorator (inject auth)
├─ Request construction → Builder + Value Object (request params)
├─ Response parsing → Data Mapper + DTO + Pattern Matching (status code)
├─ Retry on transient errors → Retry + Circuit Breaker + Timeout
├─ Rate limit respect → Rate Limiter + Observer (throttle when approaching limit)
├─ Pagination → Iterator (abstract pagination behind iterator)
│   └─ Client.list_users() returns an Iterator that auto-fetches next pages
├─ Async and sync variants → Bridge (sync/async abstraction) + Future/Promise
├─ Multiple API versions → Adapter + Abstract Factory (per version)
├─ Error handling → Exception Hierarchy + Result Type + Guard Clause
├─ Logging/debugging → Observer + Decorator (log request/response if debug=True)
└─ Testing → Test Double (fake HTTP) + Builder (test requests) + AAA
```

### "I'm implementing a multi-step form or wizard UI"

```
Building a multi-step form or wizard (UI pattern)?
├─ Step management → State Pattern (step FSM) + Command (advance/retreat)
├─ Step validation → Guard Clause + Specification (per step rules)
├─ Form data accumulation → Builder (accumulate data across steps)
├─ Draft saving → Memento (save incomplete form) + Repository
├─ Conditional steps → State + Strategy (next step based on answers)
├─ Async validation (e.g., check email taken) → Future/Promise + Guard Clause
├─ Navigation (back/next/skip) → Command + Memento (back = restore snapshot)
├─ Form submission → Saga (validate all → persist → notify → redirect)
├─ Error display → Result Type (per field) + Null Object (no error = empty)
├─ Prefill / default values → Prototype (clone default form state) + Builder
└─ Testing → State + Test Data Builder + Command (each navigation action) + AAA
```

### "I'm implementing user preferences or settings management"

```
Implementing user preferences or settings?
├─ Preference schema → Value Object (each setting is a typed Value Object)
│   └─ Never raw strings/ints — use Theme, Language, NotificationFrequency types
├─ Storage → Repository (preferences) + Unit of Work
├─ Hierarchical defaults → Chain of Responsibility
│   └─ user setting → org default → system default (each layer is a Handler)
├─ Live preference application → Observer (notify UI on change) + Strategy
├─ Type-safe access → Builder (typed preference accessor) + Guard Clause
├─ Preference migration → Adapter (old key format → new key format) + Visitor
├─ Preference export/import → Data Mapper + DTO (serializable snapshot)
├─ Sensitive preferences (encrypted) → Decorator (encrypt on write, decrypt on read)
├─ Per-device preferences → Aggregate (user has multiple device prefs)
└─ Testing → Test Data Builder + Repository stub + Observer spy + AAA
```

### "I'm building a microservice platform or chassis"

```
Building a microservice chassis or platform?
├─ Common middleware for all services → Sidecar + Decorator
│   └─ Auth, tracing, metrics, health — injected without changing service code
├─ Service registration → Service Discovery + Observer (auto-register on start)
├─ Inter-service communication → API Gateway + Circuit Breaker + Retry + Timeout
├─ Shared observability → Observer + Decorator (consistent tracing format)
├─ Shared config → Builder + Observer + Strategy (config source priority)
├─ Service contract → Specification (per-endpoint contract) + Test Double
├─ Cross-service transactions → Saga + Message Queue + Dead Letter Queue
├─ Service isolation → Bulkhead + Thread Pool + Rate Limiter
├─ Chassis as SDK → Builder + Facade + DI (services configure their chassis)
├─ Plugin system for cross-cutting concerns → Microkernel + Factory + Observer
└─ Testing → Test Double (fake service) + Sidecar (test mode) + Builder + AAA
```

### "I'm implementing dependency injection or IoC container"

```
Implementing a DI container or IoC system?
├─ Component registration → Factory + Builder (register: bind interface → implementation)
│   └─ Builder: container.bind(DatabasePort).to(PostgresAdapter).as_singleton()
├─ Scope management → Strategy (singleton, transient, scoped per request)
├─ Lazy resolution → Lazy Evaluation + Proxy (resolve on first use)
├─ Circular dependency detection → Visitor (dependency graph traversal)
│   └─ Specification: cycle_exists(dep_graph)
├─ Factory-based resolution → Factory Method (let container call factory)
├─ Module organization → Module pattern (group registrations) + Facade
├─ Testing → Swap bindings in test container; all Test Doubles registered via DI
│   └─ Hexagonal: ports are the interfaces; adapters are the bindings
├─ Decorator support → Decorator (wrap resolved service with cross-cutting behavior)
└─ Validation → Guard Clause (all deps resolvable at startup, not runtime)
```

### "I'm building an import or export system"

```
Building an import or export system?
├─ Multiple formats → Strategy (CSV, JSON, XML, Excel) + Abstract Factory
├─ Large file handling → Iterator + Lazy Evaluation + Pipe and Filter
│   └─ Never load entire file in memory; stream through pipeline
├─ Validation during import → Guard Clause + Specification (per row/field)
├─ Schema mapping → Data Mapper + DTO (source schema → domain model)
├─ Error collection → Result Type (per row) + Dead Letter Queue (failed rows)
├─ Progress reporting → Observer + State (running/paused/done/failed)
├─ Retry partial failures → Retry + Command (re-import failed rows)
├─ Idempotent imports → Identity Map (track imported IDs) + Guard Clause
├─ Export filtering → Specification + Repository + Iterator (filtered export)
├─ Export templating → Template Method (header → rows → footer) + Strategy
└─ Testing → Test Data Builder (sample files) + Strategy (test formatter) + AAA
```

---

## 🔀 Pattern Combination Scenarios

These are real-world compound use cases showing how patterns work together. Every
non-trivial feature should aim to use **4–8 patterns in combination**.

### Scenario 1: E-Commerce Checkout Flow

```
Feature: Process a customer order

Patterns applied (use all of these together):
│
├─ INPUT VALIDATION
│   ├─ Guard Clause — validate non-null items, positive amounts, valid address
│   ├─ Value Object — Money (amount + currency), Address, ProductId
│   └─ Specification — "is_eligible_for_checkout" (active account, items in stock)
│
├─ DOMAIN MODEL
│   ├─ Aggregate — Order is the root; OrderLine are children
│   ├─ State Pattern — Order: Draft → Confirmed → Paid → Shipped → Delivered
│   └─ Observer — OrderConfirmed, OrderPaid domain events
│
├─ PERSISTENCE
│   ├─ Repository — OrderRepository.save(order), .find_by_id(id)
│   ├─ Unit of Work — commit order + inventory update atomically
│   └─ Identity Map — avoid loading same order twice per request
│
├─ APPLICATION LAYER
│   ├─ Service Layer — CheckoutService.checkout(cart, payment_info)
│   ├─ Command — CheckoutCommand (carries all input data)
│   └─ DTO — OrderConfirmationDTO (response, no domain leakage)
│
├─ PAYMENT PROCESSING
│   ├─ Strategy — PaymentStrategy (CreditCard, PayPal, Crypto)
│   ├─ Circuit Breaker — protect against payment gateway failures
│   ├─ Retry — retry transient payment failures with backoff
│   └─ Saga — coordinate payment + inventory + shipping as a saga
│
└─ NOTIFICATIONS
    ├─ Observer — listen to OrderPaid event, trigger notifications
    └─ Strategy — NotificationStrategy (email, SMS, push)
```

### Scenario 2: Authenticated REST API Endpoint

```
Feature: PUT /api/v1/users/{id} — update user profile

Patterns applied (layer by layer):
│
├─ HTTP MIDDLEWARE PIPELINE (Chain of Responsibility + Decorator)
│   ├─ Rate Limiter (Proxy) — throttle per IP/user
│   ├─ Authentication (Strategy) — JWT, API key, session
│   ├─ Authorization (Proxy + Guard Clause) — "can update this user?"
│   └─ Request parsing (Guard Clause + Value Object)
│
├─ INPUT LAYER
│   ├─ Guard Clause — validate all fields before processing
│   ├─ Fail-Fast — reject invalid inputs immediately
│   ├─ Value Object — Email, PhoneNumber, DisplayName (validated types)
│   └─ DTO (UpdateUserRequest) — typed input object
│
├─ APPLICATION LAYER
│   ├─ Service Layer — UserService.update_profile(user_id, request)
│   ├─ Specification — validate business rules (e.g., email uniqueness)
│   └─ Unit of Work — wrap DB changes in transaction
│
├─ DATA LAYER
│   ├─ Repository — UserRepository.find_by_id(id), .save(user)
│   ├─ Data Mapper — map domain User to/from DB row
│   └─ Identity Map — avoid loading same user twice
│
├─ OUTPUT LAYER
│   ├─ DTO (UserResponseDTO) — shaped output (no password hash!)
│   └─ Result Type / Exception Hierarchy — typed error responses
│
└─ OBSERVABILITY
    ├─ Decorator — log every request (timing, status)
    └─ Observer — emit UserUpdated event to audit log
```

### Scenario 3: Background Job Processor

```
Feature: Process uploaded files asynchronously

Patterns applied:
│
├─ JOB SUBMISSION
│   ├─ Command — ProcessFileCommand(file_id, options)
│   ├─ Builder — JobBuilder.for_file(id).with_priority(HIGH).build()
│   └─ Message Queue — enqueue command for async processing
│
├─ WORKER POOL
│   ├─ Producer-Consumer — queue feeds workers
│   ├─ Thread Pool — N worker goroutines/threads
│   └─ Bulkhead — separate pools per file type (video, image, document)
│
├─ JOB EXECUTION
│   ├─ Template Method — validate → process → store → notify skeleton
│   ├─ Strategy — processing algorithm per file type
│   ├─ Pipe and Filter — each processing stage is a filter
│   └─ State Pattern — Job: Queued → Running → Done → Failed
│
├─ ERROR HANDLING
│   ├─ Retry — retry transient failures with exponential backoff
│   ├─ Circuit Breaker — stop if downstream storage is down
│   ├─ Dead Letter Queue — failed jobs go here for inspection
│   └─ Result Type — each stage returns Ok/Err
│
└─ OBSERVABILITY
    ├─ Observer — emit progress events (10%, 50%, 100%)
    ├─ Decorator — wrap each stage with timing metrics
    └─ Event Sourcing — append-only log of all job state changes
```

### Scenario 4: Real-Time Dashboard with Live Updates

```
Feature: Dashboard showing live metrics, auto-updating

Patterns applied:
│
├─ DATA LAYER (write side)
│   ├─ CQRS — commands write to event log, queries read from projections
│   ├─ Event Sourcing — all state changes as events
│   └─ Observer — emit metric events as they occur
│
├─ DATA LAYER (read side)
│   ├─ CQRS — dedicated read model optimized for dashboard queries
│   ├─ Repository — MetricsRepository with optimized read queries
│   └─ Memoization — cache expensive aggregations with short TTL
│
├─ REAL-TIME DELIVERY
│   ├─ Publish-Subscribe — broadcast metric updates to connected clients
│   ├─ Observer — server-side listeners push to Pub-Sub
│   └─ Flyweight — share static metadata across many live connections
│
├─ FRONTEND
│   ├─ MVVM — ViewModel exposes observable metric values
│   ├─ Observer — ViewModel subscribes to Pub-Sub channel
│   └─ Lazy Evaluation — defer rendering until data arrives
│
└─ RESILIENCE
    ├─ Fallback — show cached/stale data if live feed drops
    ├─ Circuit Breaker — protect against backend overload
    └─ Rate Limiter — throttle update frequency per client
```

### Scenario 5: Microservice with Full Resilience Stack

```
Feature: ProductCatalog microservice called from API Gateway

Patterns applied (outer to inner):
│
├─ ENTRY (API Gateway)
│   ├─ API Gateway — single entry point
│   ├─ Rate Limiter — per-client throttling
│   ├─ Sidecar — auth, tracing, TLS termination
│   └─ Backend-for-Frontend — mobile vs web responses differ
│
├─ SERVICE RESILIENCE
│   ├─ Circuit Breaker — if downstream DB is down, open circuit
│   ├─ Bulkhead — separate thread pools for read vs write
│   ├─ Retry — transient DB errors retried with jitter
│   └─ Timeout — every external call bounded
│
├─ SERVICE LAYER
│   ├─ Service Layer — ProductService orchestrates operations
│   ├─ Command (CQRS) — GetProductQuery, UpdateProductCommand
│   └─ Specification — product search filters
│
├─ DATA ACCESS
│   ├─ Repository — ProductRepository (abstracted from DB type)
│   ├─ Identity Map — avoid loading same product twice per request
│   ├─ Lazy Loading — load variants only when requested
│   └─ DTO — ProductDTO, ProductListDTO (tailored response shapes)
│
└─ OBSERVABILITY
    ├─ Decorator — wrap every service method with metrics
    ├─ Observer — emit domain events for downstream consumers
    └─ Sidecar — collect metrics, ship logs, trace propagation
```

### Scenario 6: ML Data Pipeline

```
Feature: Train ML model from raw data files

Patterns applied:
│
├─ DATA INGESTION
│   ├─ Abstract Factory — DataSourceFactory (CSV, Parquet, DB, API)
│   ├─ Adapter — normalize each source to a common DataFrame interface
│   └─ Iterator + Lazy Evaluation — stream large datasets without loading all
│
├─ PIPELINE STAGES (Pipe and Filter)
│   ├─ Filter 1: Validation — Guard Clause + Specification per field
│   ├─ Filter 2: Cleaning — Strategy (imputation, outlier removal)
│   ├─ Filter 3: Feature Engineering — Template Method (base + custom features)
│   ├─ Filter 4: Splitting — Strategy (random, time-based, stratified)
│   └─ Filter 5: Training — Strategy (algorithm: RandomForest, XGBoost, etc.)
│
├─ EXECUTION
│   ├─ Thread Pool + Future/Promise — parallel stage execution
│   ├─ Memoization — cache intermediate results for reruns
│   └─ Memento (Checkpoint) — save stage outputs for resumability
│
├─ ERROR HANDLING
│   ├─ Result Type — each stage returns Ok(DataFrame) or Err
│   ├─ Retry — retry flaky data fetches
│   └─ Dead Letter Queue — bad records routed for inspection
│
└─ EXPERIMENT TRACKING
    ├─ Observer — emit metrics at each stage
    ├─ Builder — Experiment.with_params(...).with_data(...).run()
    └─ Event Sourcing — complete audit trail of each experiment run
```

### Scenario 7: Plugin-Based Text Editor

```
Feature: Text editor with extensible plugin system

Patterns applied:
│
├─ CORE EDITOR (Microkernel)
│   ├─ Microkernel — minimal core + plugin slots
│   ├─ Composite — Document is a tree of Paragraphs, Lines, Tokens
│   └─ Iterator — traverse document nodes
│
├─ EDITING OPERATIONS
│   ├─ Command — every edit is a Command (type, delete, paste, etc.)
│   ├─ Memento — Command stores state before edit (enables undo)
│   └─ Observer — emit DocumentChanged events on every Command
│
├─ PLUGIN SYSTEM
│   ├─ Factory — PluginFactory.load(path) instantiates plugins
│   ├─ Observer — plugins subscribe to document events
│   ├─ Decorator — plugins wrap editor actions with extra behavior
│   └─ Strategy — plugins provide alternative implementations
│
├─ FEATURES (each is a plugin using patterns internally)
│   ├─ Syntax highlighting — Visitor (traverse AST) + Flyweight (shared styles)
│   ├─ Auto-complete — Strategy + Memoization (cache suggestions)
│   ├─ Spell check — Pipe and Filter + Observer (async, non-blocking)
│   └─ Search — Iterator + Strategy (regex, fuzzy, exact)
│
└─ RENDERING
    ├─ MVVM — ViewModel exposes document state as observables
    ├─ Flyweight — share Font, Style objects across many characters
    └─ Observer — ViewModel reacts to DocumentChanged events
```

### Scenario 8: Legacy Monolith Migration to Microservices

```
Feature: Incrementally extract OrderService from a monolith

Patterns applied:
│
├─ MIGRATION STRATEGY
│   ├─ Strangler Fig — route new traffic to new service, old to monolith
│   └─ Feature Flag (Strategy) — control which users hit new service
│
├─ COMPATIBILITY LAYER
│   ├─ Adapter — new service implements same interface as monolith module
│   ├─ Facade — present unified interface hiding old/new behind abstraction
│   └─ Proxy — intercept calls; route based on feature flag
│
├─ DATA MIGRATION
│   ├─ Repository — abstract data access (shared DB initially)
│   ├─ Data Mapper — map shared schema to new domain model
│   └─ Event Sourcing — new service publishes events; monolith consumes them
│
├─ COMMUNICATION
│   ├─ API Gateway — single entry point routing to old/new
│   ├─ Message Queue — async events between monolith and service
│   └─ Saga — distributed transactions spanning monolith + new service
│
└─ RESILIENCE DURING MIGRATION
    ├─ Circuit Breaker — if new service fails, fall back to monolith
    ├─ Fallback — always have a working path via old code
    └─ Observer — monitor error rates to gate feature rollout
```

### Scenario 9: Multi-Tenant SaaS Application

```
Feature: Application serving multiple isolated customer tenants

Patterns applied:
│
├─ TENANT ISOLATION
│   ├─ Abstract Factory — TenantFactory creates tenant-specific resources
│   ├─ Strategy — tenant-specific config, pricing, features
│   └─ Bulkhead — resource pools isolated per tenant
│
├─ TENANT RESOLUTION
│   ├─ Chain of Responsibility — resolve tenant from: header → JWT → subdomain
│   └─ Proxy — inject tenant context into every request transparently
│
├─ DATA ISOLATION
│   ├─ Repository — tenant-scoped repositories (every query filtered by tenant_id)
│   ├─ Specification — tenancy filter as a composable Specification
│   └─ Aggregate — tenant is the root of all domain aggregates
│
├─ FEATURE FLAGS PER TENANT
│   ├─ Strategy — per-tenant feature strategy object
│   ├─ Factory — load correct strategy based on tenant plan
│   └─ Observer — react to plan upgrades/downgrades at runtime
│
├─ BILLING / METERING
│   ├─ Decorator — wrap service methods to count usage
│   ├─ Observer — emit UsageEvent for every billable operation
│   └─ Command + Saga — billing operations as compensatable commands
│
└─ CUSTOMIZATION
    ├─ Template Method — tenant overrides specific steps
    ├─ Decorator — add tenant-specific behavior without forking code
    └─ Microkernel — core product + tenant-specific plugins
```

### Scenario 10: Document Approval Workflow

```
Feature: Multi-step document approval with parallel reviewers

Patterns applied:
│
├─ DOCUMENT MODEL
│   ├─ State Pattern — Draft → Under Review → Approved / Rejected → Published
│   ├─ Aggregate — Document root with Comments, Annotations as children
│   └─ Value Object — DocumentId, Version, AuthorName
│
├─ WORKFLOW ENGINE
│   ├─ Command — each workflow action is a Command (Submit, Approve, Reject)
│   ├─ Chain of Responsibility — route to the right approver(s)
│   ├─ Strategy — approval rules (majority, unanimous, sequential)
│   └─ Specification — approval eligibility rules
│
├─ NOTIFICATIONS
│   ├─ Observer — emit ReviewRequested, Approved, Rejected events
│   └─ Strategy — notification channel per approver preference
│
├─ AUDIT TRAIL
│   ├─ Event Sourcing — every state change as an immutable event
│   ├─ Memento — snapshot document at approval time
│   └─ Observer — audit logger subscribes to all events
│
├─ PARALLEL REVIEW
│   ├─ Future/Promise — each reviewer gets a future for their decision
│   ├─ Thread Pool — process review assignments concurrently
│   └─ Saga — coordinate parallel reviews into a final decision
│
└─ STORAGE
    ├─ Repository — DocumentRepository + ApprovalRepository
    ├─ Unit of Work — atomic: update state + append event + send notifications
    └─ CQRS — separate read model for "pending reviews dashboard"
```

### Scenario 11: Financial Transaction System

```
Feature: Execute financial transfers with compliance and audit

Patterns applied:
│
├─ INPUT VALIDATION
│   ├─ Guard Clause — reject nulls, negative amounts, invalid accounts
│   ├─ Value Object — Money (amount + currency), AccountId, IBAN
│   ├─ Specification — business rules (daily limit, fraud check, KYC status)
│   └─ Fail-Fast — reject invalid transfers at boundary, not deep in logic
│
├─ TRANSACTION EXECUTION
│   ├─ Saga — debit source → credit destination → update ledger (with compensation)
│   ├─ Command — each step is a Command (DebitCommand, CreditCommand)
│   ├─ Unit of Work — ACID transaction covering all DB writes
│   └─ Result Type — every step returns Ok/Err, no hidden exceptions
│
├─ CONSISTENCY
│   ├─ Event Sourcing — transaction log is the source of truth
│   ├─ CQRS — balance queries served from read model (not event log)
│   └─ Aggregate — Account aggregate enforces balance invariants
│
├─ COMPLIANCE
│   ├─ Decorator — wrap execution with compliance checks
│   ├─ Observer — emit TransactionCompleted for compliance systems
│   └─ Chain of Responsibility — route to different compliance handlers by amount
│
└─ RESILIENCE
    ├─ Idempotency (Identity Map) — deduplicate double-submitted transactions
    ├─ Retry — retry transient infrastructure errors
    ├─ Circuit Breaker — protect against external payment rail failures
    └─ Dead Letter Queue — failed transactions for manual review
```

### Scenario 12: Chat Application

```
Feature: Real-time group chat with history and media

Patterns applied:
│
├─ CONNECTION MANAGEMENT
│   ├─ Reactor — event loop handles thousands of WebSocket connections
│   ├─ Actor Model — each connected user is an actor with a mailbox
│   └─ Bulkhead — separate thread/connection pools per chat room
│
├─ MESSAGE FLOW
│   ├─ Observer — room broadcasts to all connected members
│   ├─ Mediator — ChatRoom mediates between user actors
│   ├─ Command — SendMessageCommand, EditMessageCommand, DeleteMessageCommand
│   └─ Publish-Subscribe — topic per room for message routing
│
├─ MEDIA HANDLING
│   ├─ Strategy — media type handler (image, video, file, link preview)
│   ├─ Pipe and Filter — upload → validate → resize → store → notify
│   └─ Message Queue — async media processing
│
├─ HISTORY
│   ├─ Event Sourcing — all messages as events (supports replay)
│   ├─ CQRS — write messages to event log, query from indexed read model
│   └─ Iterator + Lazy Evaluation — paginate history without loading all
│
├─ SEARCH
│   ├─ Repository — MessageRepository with full-text search
│   └─ Specification — filter by date range, author, keyword
│
└─ NOTIFICATIONS
    ├─ Observer — offline users get push notifications on new messages
    ├─ Strategy — notification channel (push, email, SMS) per preference
    └─ Rate Limiter — prevent notification spam (max N per minute)
```

### Scenario 13: User Registration with Email Verification

```
Feature: Register a new user, verify email, then grant access

Patterns applied:
│
├─ INPUT VALIDATION
│   ├─ Guard Clause — reject missing fields, invalid email format
│   ├─ Value Object — Email, Password (hashed), Username
│   ├─ Specification — email_not_taken, username_not_taken
│   └─ Fail-Fast — check uniqueness before any persistence
│
├─ REGISTRATION FLOW (Saga)
│   ├─ Saga — create_account → send_verification → await_confirm → activate
│   ├─ Command — CreateAccountCommand, SendVerificationCommand, ActivateCommand
│   └─ State Pattern — Account: Unverified → Verified → Active → Suspended
│
├─ TOKEN MANAGEMENT
│   ├─ Value Object — VerificationToken (cryptographically random, expiry)
│   ├─ Repository — TokenRepository (store, find, invalidate)
│   └─ Guard Clause — validate token not expired, not already used
│
├─ EMAIL DELIVERY
│   ├─ Strategy — EmailStrategy (SMTP, SendGrid, SES)
│   ├─ Template Method — email layout with customizable body
│   ├─ Retry — retry failed sends with backoff
│   └─ Dead Letter Queue — undeliverable emails for support
│
├─ OBSERVABILITY
│   ├─ Observer — emit UserRegistered, EmailVerified domain events
│   └─ Event Sourcing — full audit trail of account creation steps
│
└─ TESTING
    ├─ Test Data Builder — build test users in various states
    ├─ Test Double — fake email sender, fake token generator
    └─ State verification — assert each Saga transition
```

### Scenario 14: Search with Facets and Ranked Results

```
Feature: Product search with filters, facets, and relevance ranking

Patterns applied:
│
├─ QUERY BUILDING
│   ├─ Builder — SearchQuery.for_text("laptop").in_category("electronics")
│   │             .price_between(500, 1500).sorted_by(RELEVANCE).page(1)
│   ├─ Specification — each filter clause is a composable Specification
│   └─ Value Object — SearchQuery (immutable, equality by value)
│
├─ SEARCH EXECUTION
│   ├─ Strategy — SearchStrategy (database full-text, Elasticsearch, in-memory)
│   ├─ Abstract Factory — SearchFactory creates correct Strategy per environment
│   └─ Adapter — normalize each backend's result to common SearchResult shape
│
├─ FACET COMPUTATION
│   ├─ Visitor — FacetVisitor traverses result set, counts per facet
│   ├─ Composite — facets composed from Specifications (Category AND Price)
│   └─ Memoization — cache facet counts for expensive queries (short TTL)
│
├─ RESULT RANKING
│   ├─ Strategy — RankingStrategy (text relevance, popularity, freshness, price)
│   ├─ Decorator — add boost factors (sponsored, in-stock) to base ranker
│   └─ Chain of Responsibility — apply ranking rules in priority order
│
├─ PERFORMANCE
│   ├─ Proxy (caching) — cache common query results for N seconds
│   ├─ Lazy Evaluation — defer facet computation until needed
│   └─ Identity Map — avoid loading same product twice per request
│
└─ DELIVERY
    ├─ DTO — SearchResultDTO (tailored: list view vs detail view differ)
    ├─ Iterator — paginate results lazily
    └─ Observer — log search queries for analytics + personalization
```

### Scenario 15: Feature Flag System with Gradual Rollout

```
Feature: Toggle features per user, org, or percentage

Patterns applied:
│
├─ FLAG DEFINITION
│   ├─ Builder — Flag.named("dark_mode").enabled_for(10%).with_targeting(...).build()
│   ├─ Value Object — FlagKey, RolloutPercentage, UserSegment (typed, validated)
│   └─ Repository — FlagRepository.find_by_key(key)
│
├─ EVALUATION (Chain of Responsibility)
│   ├─ Handler 1: User override → check explicit user-level flag
│   ├─ Handler 2: Experiment assignment → hash(user_id + flag_key) → bucket
│   ├─ Handler 3: Org/tenant flag → check org-level setting
│   ├─ Handler 4: Global default → fallback to global on/off
│   └─ Each Handler checks its Specification before evaluating
│
├─ ROLLOUT TARGETING
│   ├─ Specification — UserSegment spec (beta users, paid plan, geography)
│   ├─ Strategy — RolloutStrategy (percentage hash, ring deployment, canary)
│   └─ Composite — combine specs: (is_beta_user AND NOT is_admin)
│
├─ RUNTIME CONFIG
│   ├─ Observer — reload flags on config change without restart
│   ├─ Proxy — cache flag values; refresh in background
│   └─ Null Object — disabled flag returns null/default behavior
│
├─ AUDIT
│   ├─ Observer — emit FlagChanged events on every update
│   └─ Event Sourcing — full history: who changed, old value, new value, when
│
└─ TESTING
    ├─ Strategy — inject test FlagStrategy that returns deterministic values
    ├─ Test Double (Stub) — FlagService returning fixed values
    └─ Builder — build test flags for each scenario
```

### Scenario 16: E-Commerce Shopping Cart with Session

```
Feature: Shopping cart with persistent session, discounts, and checkout

Patterns applied:
│
├─ CART MODEL
│   ├─ Aggregate — Cart is root; CartLine, CartCoupon are children
│   ├─ Value Object — ProductId, Quantity, Money (price), CouponCode
│   └─ Guard Clause — validate quantity > 0, product exists, coupon valid
│
├─ CART OPERATIONS (Command)
│   ├─ AddItemCommand, RemoveItemCommand, UpdateQuantityCommand
│   ├─ ApplyCouponCommand, RemoveCouponCommand
│   └─ Memento — save cart snapshot (allows "restore abandoned cart")
│
├─ PRICING / DISCOUNTS
│   ├─ Strategy — PricingStrategy (standard, sale, loyalty, bulk discount)
│   ├─ Decorator — stack discounts: BulkDiscount(LoyaltyDiscount(BasePrice))
│   ├─ Specification — coupon eligibility (min order, product category, user tier)
│   └─ Chain of Responsibility — apply promotions in priority order
│
├─ SESSION PERSISTENCE
│   ├─ Repository — CartRepository (save/load by session or user ID)
│   ├─ Identity Map — avoid loading same cart twice per request
│   └─ Prototype — clone cart for guest → authenticated user merge
│
├─ INVENTORY RESERVATION
│   ├─ Saga — reserve stock → place order → confirm reservation
│   ├─ Observer — emit CartAbandoned if session expires without checkout
│   └─ Circuit Breaker — if inventory service is down, degrade gracefully
│
└─ TESTING
    ├─ Test Data Builder — build carts with specific items, coupons
    ├─ Command — execute and verify each cart operation
    └─ Specification — assert discount and eligibility rules
```

### Scenario 17: API Rate Limiting and Throttling Infrastructure

```
Feature: Per-client rate limiting with tiered limits and burst allowance

Patterns applied:
│
├─ LIMIT DEFINITION
│   ├─ Value Object — RateLimit (requests, window, burst) — typed, validated
│   ├─ Strategy — limit tier per client (free: 100/min, pro: 1000/min, enterprise: ∞)
│   ├─ Abstract Factory — create correct limiter per tier
│   └─ Repository — ClientTierRepository (look up client's current tier)
│
├─ LIMIT ENFORCEMENT (Proxy)
│   ├─ Proxy — rate limit proxy wraps every API handler transparently
│   ├─ Monitor — thread-safe token bucket / sliding window algorithm
│   ├─ Guard Clause — check limit before handler executes
│   └─ Chain of Responsibility — check: per-endpoint → per-user → per-IP → global
│
├─ TOKEN BUCKET IMPLEMENTATION
│   ├─ Flyweight — share bucket objects for same tier (not per-user allocation)
│   ├─ Immutability — bucket state is versioned, CAS updates (no race conditions)
│   └─ Object Pool — reuse bucket objects rather than create per request
│
├─ RESPONSE ON LIMIT
│   ├─ Result Type — return RateLimitExceeded error (not exception)
│   ├─ Null Object — placeholder response with retry-after header
│   └─ Fallback — degraded mode (serve cached response) vs hard reject
│
├─ OBSERVABILITY
│   ├─ Observer — emit RateLimitApproached (at 80%) and RateLimitHit events
│   ├─ Decorator — log all limit decisions (client, endpoint, remaining)
│   └─ Pub-Sub — broadcast limit events for billing/alerting
│
└─ TESTING
    ├─ Monitor (fake clock) — control time in tests
    ├─ Strategy — inject test tier with known limits
    └─ Test Data Builder — build clients with specific tiers
```

### Scenario 18: AI Agent with Tool Use and Memory

```
Feature: LLM-backed agent that uses tools and remembers context

Patterns applied:
│
├─ AGENT LOOP (Template Method)
│   ├─ perceive() — read inputs, retrieve memory, format context
│   ├─ reason() — call LLM with context; parse tool calls from response
│   ├─ act() — execute tool Commands; handle results
│   └─ remember() — store new knowledge; update state
│
├─ TOOL SYSTEM (Command + Registry)
│   ├─ Command — each tool is a Command (SearchWeb, WriteFile, RunCode, CallAPI)
│   ├─ Factory — ToolFactory.for_name("search") → SearchCommand instance
│   ├─ Chain of Responsibility — validate tool call → check permissions → execute
│   └─ Guard Clause — validate tool inputs before execution
│
├─ LLM INTEGRATION
│   ├─ Abstract Factory — LLMFactory (OpenAI, Anthropic, local Ollama)
│   ├─ Adapter — normalize each LLM API to a common interface
│   ├─ Builder — PromptBuilder.with_system(...).with_memory(...).with_tools(...)
│   ├─ Retry — retry on rate limits with exponential backoff
│   └─ Circuit Breaker — if LLM provider is down, fail gracefully
│
├─ MEMORY SYSTEM
│   ├─ Repository — MemoryRepository (semantic search over past interactions)
│   ├─ Memento — save/restore conversation state across sessions
│   ├─ Specification — retrieve relevant memories (by topic, recency, importance)
│   └─ Memoization — cache repeated retrievals within a session
│
├─ MULTI-AGENT COORDINATION
│   ├─ Mediator — OrchestratorAgent routes tasks to specialist agents
│   ├─ Actor Model — each agent is an actor with isolated state + message queue
│   └─ Observer — agents emit tool results; orchestrator reacts
│
└─ OBSERVABILITY
    ├─ Observer — trace every tool call, LLM invocation, memory access
    ├─ Event Sourcing — full audit trail of agent decisions
    └─ Decorator — wrap all tool calls with timing + token counting
```

### Scenario 19: Payment Processing System

```
Feature: Accept, process, and reconcile payments from multiple providers

Patterns applied:
│
├─ INPUT LAYER
│   ├─ Value Object — Money (decimal + currency; never float), CardToken, IBAN
│   ├─ Guard Clause — reject nil amounts, negative amounts, unsupported currencies
│   ├─ Specification — business rules: daily limit, KYC verified, not blocked country
│   └─ Fail-Fast — all checks before any side effects
│
├─ PROVIDER ABSTRACTION
│   ├─ Abstract Factory — PaymentGatewayFactory (Stripe, Adyen, Braintree)
│   ├─ Adapter — each provider SDK wrapped to PaymentGateway interface
│   └─ Strategy — provider selection: primary → secondary (failover)
│
├─ PAYMENT FLOW (Saga)
│   ├─ Saga — authorize → capture → settle (with compensating: void / refund)
│   ├─ Command — AuthorizeCommand, CaptureCommand, RefundCommand
│   └─ State — Payment: Initiated → Authorized → Captured → Settled → Refunded
│
├─ RESILIENCE
│   ├─ Circuit Breaker — per provider (open if >5 failures in 30s)
│   ├─ Retry — retry transient errors (timeout, 5xx) with exponential backoff + jitter
│   ├─ Fallback — switch to secondary provider if primary circuit is open
│   └─ Identity Map — idempotency key prevents double charging on retry
│
├─ COMPLIANCE AND AUDIT
│   ├─ Decorator — wrap execution with PCI DSS compliance checks
│   ├─ Event Sourcing — every state change as immutable event (full audit trail)
│   └─ Observer — emit PaymentCaptured to accounting, reporting systems
│
└─ RECONCILIATION
    ├─ CQRS — write events to log; project read model (balance, transaction list)
    ├─ Repository — TransactionRepository (find, paginate, filter by Specification)
    └─ Specification — reconcile: API state vs provider webhook state must match
```

### Scenario 20: Hotel / Resource Booking System

```
Feature: Search availability, hold, confirm, and manage reservations

Patterns applied:
│
├─ SEARCH / AVAILABILITY
│   ├─ Specification — IsAvailable(resource, checkIn, checkOut, capacity)
│   ├─ Composite — combine specs: (not_blocked AND has_capacity AND in_price_range)
│   ├─ Repository — RoomRepository.find_available(spec)
│   └─ Iterator — paginate availability windows lazily
│
├─ DOMAIN MODEL
│   ├─ Aggregate — Booking root: Room, Guest, Extras as children
│   ├─ Value Object — DateRange, Money, RoomType, BookingId
│   └─ Guard Clause — enforce min nights, max occupancy, valid dates
│
├─ HOLD AND CONFIRM (Saga)
│   ├─ Saga — hold_room → process_payment → confirm_booking (compensate on failure)
│   ├─ State — Booking: Searching → Held → Confirmed → CheckedIn → Completed
│   ├─ Monitor — serialize concurrent holds on the same room
│   └─ Scheduler — auto-release hold after 15 minutes (Command + Timeout)
│
├─ PRICING
│   ├─ Strategy — pricing algorithm (standard, weekend, seasonal, loyalty)
│   ├─ Decorator — stack modifiers: BaseRate + PeakSurcharge + MemberDiscount
│   └─ Value Object — Money (never raw float; round correctly per currency)
│
├─ NOTIFICATIONS
│   ├─ Observer — emit BookingConfirmed → trigger email, calendar invite, receipt
│   └─ Strategy — channel per guest preference (email, SMS, app push)
│
└─ PERSISTENCE AND REPORTING
    ├─ Repository + Unit of Work — atomic: update booking + debit inventory
    ├─ CQRS — separate read model for occupancy dashboard and revenue reports
    └─ Event Sourcing — full history of every booking change for audit
```

### Scenario 21: SaaS Onboarding and Tenant Provisioning

```
Feature: New organization signs up; workspace + team provisioned automatically

Patterns applied:
│
├─ REGISTRATION INPUT
│   ├─ Value Object — Email, OrgName, Plan (typed, validated, immutable)
│   ├─ Guard Clause — reject existing org names, invalid emails, unsupported plans
│   └─ Specification — domain_not_reserved, email_not_taken
│
├─ PROVISIONING SAGA
│   ├─ Saga — create_org → provision_db_schema → seed_defaults → send_welcome → activate
│   ├─ Command — each step is a Command (CreateOrgCommand, SeedDataCommand, etc.)
│   ├─ State — Org: Registering → Provisioning → Trial → Active → Suspended
│   └─ Dead Letter Queue — failed provisioning steps for ops review
│
├─ ONBOARDING WIZARD
│   ├─ State — wizard step FSM (company_info → team_invite → integrations → done)
│   ├─ Builder — accumulate answers across steps
│   ├─ Memento — save progress (user can resume after session break)
│   └─ Strategy — wizard flow varies by plan tier (solo vs team vs enterprise)
│
├─ MULTI-TENANT ISOLATION
│   ├─ Abstract Factory — TenantFactory creates scoped resources per org
│   ├─ Specification — tenant filter injected into every Repository query
│   └─ Bulkhead — resource pools isolated per tenant
│
├─ BILLING SETUP
│   ├─ Saga — create_customer → attach_payment → start_trial → schedule_first_charge
│   ├─ Strategy — billing plan implementation per tier
│   └─ Observer — emit TrialStarted for billing system + analytics
│
└─ OBSERVABILITY
    ├─ Event Sourcing — every org lifecycle event (created, activated, churned)
    ├─ Observer — emit ActivationCompleted for CRM, onboarding analytics
    └─ Decorator — trace every provisioning step with timing metrics
```

### Scenario 22: Distributed Rate Limiter Across Multiple Instances

```
Feature: Enforce per-user and per-endpoint rate limits across N service instances

Patterns applied:
│
├─ LIMIT DEFINITION
│   ├─ Value Object — RateLimit (max_requests, window_seconds, burst) — immutable
│   ├─ Strategy — tier strategy (free: 60/min, pro: 600/min, enterprise: unlimited)
│   └─ Specification — is_within_limit(user_id, endpoint, window)
│
├─ ENFORCEMENT LAYER (Proxy)
│   ├─ Proxy — rate limit proxy wraps handler transparently
│   ├─ Chain of Responsibility — check: per-endpoint → per-user → per-IP → global
│   └─ Guard Clause — reject immediately if limit exceeded; return Retry-After
│
├─ DISTRIBUTED COUNTER (shared state)
│   ├─ Adapter — CounterAdapter (wraps Redis/Memcached/DB)
│   ├─ Monitor — thread-safe local counter update + atomic remote sync
│   ├─ Read-Write Lock — concurrent reads of current count; exclusive on write
│   └─ Flyweight — share counter objects by key (not per-request allocation)
│
├─ ALGORITHMS
│   ├─ Strategy — algorithm per tier: fixed window / sliding window / token bucket
│   ├─ Immutability — bucket state versioned (CAS updates; no lock on read path)
│   └─ Memoization — cache limit configs (don't fetch from DB on every request)
│
├─ RESPONSE ON BREACH
│   ├─ Result Type — return RateLimitExceeded (not exception; caller handles)
│   ├─ Null Object — placeholder response with Retry-After header
│   └─ Fallback — degraded mode (serve cached response) vs hard reject (Strategy)
│
└─ OBSERVABILITY
    ├─ Observer — emit LimitApproached (at 80%), LimitHit, and LimitReset events
    ├─ Decorator — log all decisions: user, endpoint, remaining, window_reset_at
    └─ Event Sourcing — append-only log of all limit violations for alerting/billing
```

### Scenario 23: Recommendation Engine with Personalization

```
Feature: Serve personalized product/content recommendations in real time

Patterns applied:
│
├─ USER MODEL
│   ├─ Aggregate — UserProfile (root) with PreferenceVector, InteractionHistory
│   ├─ Value Object — UserId, InterestScore, ItemId (typed, no raw primitives)
│   └─ Observer — update profile on every user action (click, view, purchase, skip)
│
├─ ALGORITHM LAYER
│   ├─ Strategy — algorithm selection: collaborative filtering, content-based, hybrid, trending
│   ├─ Abstract Factory — algorithm factory per user segment (new, active, churned)
│   ├─ Template Method — recommend() skeleton: load_candidates → score → filter → rank → trim
│   └─ Decorator — add post-processors: dedup + diversity enforcement + sponsored boost
│
├─ CANDIDATE RETRIEVAL
│   ├─ Repository — CandidateRepository (ANN index, trending store, curated lists)
│   ├─ Specification — filter out: seen items, out-of-stock, blocked categories
│   └─ Iterator + Lazy Evaluation — stream candidates; stop when N qualified found
│
├─ PERFORMANCE
│   ├─ Memoization — cache recommendations per (user_id, context) for ~60s
│   ├─ Proxy — serve cached recommendations; refresh in background
│   └─ Flyweight — share item metadata objects across all user recommendation lists
│
├─ A/B TESTING
│   ├─ Feature Flag (Strategy) — assign user to algorithm variant
│   └─ Observer — track exposure, clicks, conversions per variant
│
└─ RESILIENCE AND FALLBACK
    ├─ Circuit Breaker — if ML model is down, open circuit
    ├─ Fallback — serve trending/popular items when personalization unavailable
    └─ Timeout — bound recommendation latency (never block page load)
```

---

## 📈 Pattern Progression: Start Simple, Add as Complexity Grows

> **Don't apply all patterns at once.** Apply them as the complexity demands it.
> This table shows how a typical component evolves from minimal to fully-patterned.

### Progression for a Data-Accessing Service

```
Stage 1: First working version (1 pattern)
  └─ Guard Clause — at minimum, validate inputs

Stage 2: Making it testable (3 patterns)
  ├─ Dependency Injection — inject the DB dependency
  ├─ Repository — abstract the data access
  └─ Guard Clause

Stage 3: Production-ready (6 patterns)
  ├─ Service Layer — defined application boundary
  ├─ Repository + Unit of Work — safe persistence
  ├─ DTO — clean input/output shapes
  ├─ Guard Clause + Fail-Fast — robust validation
  └─ DI — full inversion of control

Stage 4: Observable and resilient (9 patterns)
  ├─ All of Stage 3
  ├─ Observer — emit domain events
  ├─ Decorator — add logging/metrics
  ├─ Circuit Breaker — protect downstream calls
  └─ Result Type — typed error handling

Stage 5: Scalable and auditable (12+ patterns)
  ├─ All of Stage 4
  ├─ CQRS — separate read/write models
  ├─ Event Sourcing — full audit trail
  ├─ Specification — composable query/business rules
  └─ Identity Map + Lazy Loading — query optimization
```

### Progression for a Feature Flag

```
Stage 1: Boolean config value
  └─ Nothing — but this is already technical debt

Stage 2: Strategy Pattern (1 pattern)
  └─ Strategy — enabled/disabled are two strategies

Stage 3: Testable and injectable (3 patterns)
  ├─ Strategy
  ├─ DI — inject FlagService
  └─ Null Object — disabled = NullObject

Stage 4: Dynamic and safe (6 patterns)
  ├─ Strategy + DI + Null Object
  ├─ Repository — store flag configs
  ├─ Observer — react to flag changes
  └─ Guard Clause — validate flag configs

Stage 5: Full feature flag system (10+ patterns)
  └─ See Scenario 15 above
```

---

## 🧩 Minimum Pattern Set for Every Component Type

> Apply at **minimum** these patterns for each component type. More is better.

| Component Type | Minimum Patterns Required |
|----------------|--------------------------|
| **Any function/method** | Guard Clause + Result Type |
| **Any class** | SRP + DI (inject dependencies) |
| **Domain entity** | Value Object (IDs/primitives) + Guard Clause + Aggregate |
| **Service class** | Service Layer + Repository + Guard Clause + DTO |
| **Repository** | Repository + Identity Map + Specification |
| **External API call** | Adapter + Facade + Circuit Breaker + Retry + Timeout |
| **Event handler** | Command + Observer + Guard Clause |
| **Batch/job** | Command + Template Method + Retry + Dead Letter Queue |
| **HTTP endpoint** | Guard Clause + DTO + Service Layer + Result Type |
| **Configuration** | Builder + Value Object + Observer |
| **Cache** | Proxy + Memoization + Observer (invalidation) |
| **Queue consumer** | Command + Retry + Dead Letter Queue + State |
| **Plugin** | Microkernel + Factory + Observer + Guard Clause |
| **Test** | AAA or GWT + Test Data Builder + Test Doubles + DI |
| **CLI command** | Command + Guard Clause + Builder + Result Type |
| **Domain rule** | Specification + Composite (AND/OR/NOT) |

---

## 🎯 "When Am I Allowed to Skip Patterns?" — Never

> **There is no code complex enough to skip patterns and no code simple enough that
> patterns don't apply.** The following are common rationalizations to avoid — and
> the pattern that should be applied instead:

| Temptation | Problem | Apply Instead |
|------------|---------|---------------|
| "It's just a simple function" | Functions grow; no isolation | Guard Clause + Result Type |
| "I'll just use a boolean flag parameter" | Flag parameters indicate mixed responsibilities | Strategy or State |
| "I'll just check for null" | Null checks spread everywhere | Null Object or Result Type |
| "I'll hardcode this dependency" | Impossible to test or swap | Dependency Injection + DIP |
| "I'll just add another if/elif" | Open/Closed violation | Strategy + Factory |
| "I'll just put it in the model" | SRP violation | Repository + Service Layer |
| "I'll use a global config dict" | Hidden coupling, hard to test | Builder + DI + Observer |
| "I'll call the DB directly from the controller" | No separation of concerns | Repository + Service Layer + DTO |
| "I'll throw a generic Exception" | Callers can't handle specifically | Exception Hierarchy + Result Type |
| "I'll just pass the raw dict around" | Untyped, no validation, leaks internals | Value Object + DTO + Guard Clause |
| "I'll write the retry loop inline" | No structure, no DLQ, no observability | Retry Pattern + Dead Letter Queue |
| "I'll just sleep and poll" | Busy-wait; no event model | Observer + Reactor + Future/Promise |
| "I'll add a flag to the constructor" | Mixed concerns in construction | Builder + Factory + Strategy |
| "I'll just copy-paste this class" | Duplication, divergence | Template Method + Strategy + DRY |
| "I'll put the business rule in the SQL" | Logic in wrong layer, untestable | Specification + Service Layer |
| "I'll hardcode the third-party URL" | Vendor lock-in, untestable | Adapter + Facade + DI |
| "I'll handle errors in the caller each time" | Inconsistent, scattered handling | Exception Hierarchy + Result Type |
| "I'll add another method to this class" | God class growth, SRP violation | Extract to new class + DI + SRP |
| "I'll use a static method for everything" | No polymorphism, no injection | Strategy + DI + Factory |
| "I'll store state in a global variable" | Race conditions, hidden coupling | Actor Model or Immutability + DI |
| "I'll just print to debug" | Not structured, not removable | Observer + Decorator (logging strategy) |
| "I'll add the feature directly to the model" | Fat domain model, SRP violation | Service Layer + Specification + Command |
| "I'll use inheritance to share code" | Fragile base class, LSP risk | Strategy + Composition + DIP |
| "I'll write async code with raw threads" | Race conditions, hard to test | Actor Model + Future/Promise + Monitor |
| "I'll do it all synchronously for simplicity" | Blocks, poor UX, scaling wall | Future/Promise + Message Queue + Reactor |
| "The DB schema is my domain model" | Tight coupling | Data Mapper + Value Object |
| "I'll handle the error in the caller" | Inconsistent error handling | Result Type + Exception Hierarchy |
| "I'll just add a global variable" | Hidden state, impossible to test | Singleton with DI or Flyweight |
| "I'll copy-paste this class and change one method" | Code duplication | Template Method or Strategy |
| "I'll write async code inline" | Hard to test, race conditions | Future/Promise + Actor Model |
| "I'll retry this in a loop" | No structure, no observability | Retry pattern + Dead Letter Queue |
| "I'll add logging with print statements" | Non-structured, non-removable | Decorator + Observer (logging) |
| "The UI can talk to the DB directly" | No separation of concerns | Repository + Service Layer + DTO |
| "I'll add a method to this class for the new feature" | God class growth | SRP + new class + DI |

---

## 🔗 Pattern Synergies: Best Combinations

These patterns are **always better together**. When you use one, apply its partners:

| Primary Pattern | Always Pair With | Why |
|----------------|-----------------|-----|
| Repository | Unit of Work + Identity Map + Specification | Batch changes atomically; avoid N+1; filter cleanly |
| Observer | Event Bus (in-process) or Pub-Sub (distributed) | Observers shouldn't call each other directly |
| Strategy | Factory (to select) + DI (to inject) | Strategy is useless if selection logic is hardcoded |
| Decorator | Chain of Responsibility | Decorators naturally form a chain |
| Command | Memento (undo) + Queue (async) | Commands without undo or queuing are half-implemented |
| State | Observer (emit transitions) + Guard Clause | State changes without events are invisible |
| Aggregate | Guard Clause + Repository | Aggregates enforce invariants; Repository loads/saves them |
| Saga | Command (each step) + Dead Letter Queue | Saga steps without DLQ lose failed compensations |
| Circuit Breaker | Retry + Fallback + Observer | Circuit Breaker alone doesn't retry or degrade gracefully |
| Specification | Composite (AND/OR/NOT) + Repository | Specs alone don't compose; Repository applies them to queries |
| Service Layer | Guard Clause + DTO (input) + DTO (output) | Service boundary is meaningless without validation and typed I/O |
| Event Sourcing | CQRS + Memento (snapshots) | Event log grows unbounded; CQRS and snapshots make it usable |
| Pipe and Filter | Strategy (each filter) + Template Method | Filters should be interchangeable; skeleton defines order |
| Actor Model | Immutability + Message Queue | Actors sharing mutable state defeat the purpose |
| DI | Factory (complex creation) + DIP (interface, not class) | DI without interfaces still couples to implementations |
| Proxy | Decorator (add behavior) + Guard Clause (protect) | Proxy intercepts; decorate to add; guard to protect |
| Value Object | Immutability + Guard Clause (in constructor) | Value Objects must be validated and never mutated |
| CQRS | Event Sourcing + Repository (per side) | CQRS write side needs an event log; read side needs its own Repository |
| Test Data Builder | Prototype (clone base) + DI (inject into SUT) | Build test data once; clone variants; inject cleanly |
| Memoization | Proxy (transparent) + Observer (invalidation) | Memoization without invalidation serves stale data forever |

---

## ✅ Code Review Checklist: Pattern Coverage

Use this checklist when reviewing any code that doesn't have obvious pattern coverage:

### Every Class/Module
- [ ] Does it have exactly ONE reason to change? (SRP)
- [ ] Are all dependencies injected, not constructed internally? (DI + DIP)
- [ ] Are inputs validated at the top of every public method? (Guard Clause)
- [ ] Are errors surfaced explicitly rather than silently swallowed? (Result Type / Fail-Fast)
- [ ] Can the class be extended without modification? (OCP)

### Every Service or Use Case
- [ ] Is it behind a Service Layer boundary?
- [ ] Are DTOs used for input and output (no domain object leakage)?
- [ ] Is data access behind a Repository?
- [ ] Is the transaction boundary wrapped in Unit of Work?
- [ ] Are domain events emitted for significant state changes? (Observer)

### Every External Call (DB, API, queue, cache)
- [ ] Is the dependency behind an Adapter or Repository interface?
- [ ] Is there a Circuit Breaker if the external system can fail?
- [ ] Is there a Retry with exponential backoff?
- [ ] Is there a Timeout to prevent indefinite blocking?
- [ ] Is there a Fallback when all else fails?

### Every Conditional / Switch Statement
- [ ] `if type == X:` → replace with Strategy + Factory
- [ ] `if feature_enabled:` → replace with Feature Flag (Strategy + Null Object)
- [ ] `if x is None:` → replace with Null Object or Result Type
- [ ] Multiple elif chains → Chain of Responsibility or Visitor

### Every Loop Over a Collection
- [ ] Is the collection exposed? → Use Iterator
- [ ] Is it computing something per element? → Visitor
- [ ] Is it transforming? → Higher-Order Functions + Immutability
- [ ] Is it large/lazy? → Lazy Evaluation + Producer-Consumer

### Every Test
- [ ] Is the SUT's dependencies injectable? (DI — if not, you can't test it)
- [ ] Is the test structured AAA or GWT?
- [ ] Is test data built with a Test Data Builder?
- [ ] Are external dependencies replaced with Test Doubles?
- [ ] Does the test cover the error path, not just the happy path?

---

## ⚡ Quick Pattern Lookup

### GoF Creational (Gang of Four)
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Factory Method | Subclass decides which object to create | `references/creational/factory.md` |
| Abstract Factory | Create families of related objects | `references/creational/abstract-factory.md` |
| Builder | Construct complex objects step by step | `references/creational/builder.md` |
| Prototype | Clone existing objects | `references/creational/prototype.md` |
| Singleton | Ensure exactly one instance | `references/creational/singleton.md` |

### GoF Structural
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Adapter | Convert one interface to another | `references/structural/adapter.md` |
| Bridge | Separate abstraction from implementation | `references/structural/bridge.md` |
| Composite | Treat tree of objects uniformly | `references/structural/composite.md` |
| Decorator | Add behavior by wrapping | `references/structural/decorator.md` |
| Facade | Simplify a complex subsystem | `references/structural/facade.md` |
| Flyweight | Share data to save memory | `references/structural/flyweight.md` |
| Proxy | Control access with a surrogate | `references/structural/proxy.md` |

### GoF Behavioral
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Chain of Responsibility | Pass request along a handler chain | `references/behavioral/chain-of-responsibility.md` |
| Command | Encapsulate action as object | `references/behavioral/command.md` |
| Interpreter | Evaluate language grammar | `references/behavioral/interpreter.md` |
| Iterator | Traverse without exposing internals | `references/behavioral/iterator.md` |
| Mediator | Centralize object communication | `references/behavioral/mediator.md` |
| Memento | Snapshot and restore state | `references/behavioral/memento.md` |
| Observer | Notify subscribers of changes | `references/behavioral/observer.md` |
| State | Change behavior when state changes | `references/behavioral/state.md` |
| Strategy | Select algorithm at runtime | `references/behavioral/strategy.md` |
| Template Method | Skeleton algorithm with customizable steps | `references/behavioral/template-method.md` |
| Visitor | Add operations without changing classes | `references/behavioral/visitor.md` |

### Additional Object Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Null Object | Default behavior instead of null | `references/behavioral/null-object.md` |
| Object Pool | Reuse expensive objects | `references/creational/object-pool.md` |
| Dependency Injection | Invert control of dependencies | `references/creational/dependency-injection.md` |
| Module | Encapsulate cohesive functionality | `references/structural/module.md` |

### SOLID Principles
| Principle | One-line summary | Reference |
|-----------|-----------------|-----------|
| Single Responsibility (SRP) | One class, one reason to change | `references/solid-principles/single-responsibility.md` |
| Open/Closed (OCP) | Open for extension, closed for modification | `references/solid-principles/open-closed.md` |
| Liskov Substitution (LSP) | Subtypes substitutable for base types | `references/solid-principles/liskov-substitution.md` |
| Interface Segregation (ISP) | Small, specific interfaces | `references/solid-principles/interface-segregation.md` |
| Dependency Inversion (DIP) | Depend on abstractions, not concretions | `references/solid-principles/dependency-inversion.md` |

### Architectural Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Repository | Abstract data access behind collection-like interface | `references/architectural/repository.md` |
| Unit of Work | Track and commit changes as a transaction | `references/architectural/unit-of-work.md` |
| Service Layer | Coordinate business operations | `references/architectural/service-layer.md` |
| MVC | Model-View-Controller | `references/architectural/mvc.md` |
| MVVM | Model-View-ViewModel (data binding) | `references/architectural/mvvm.md` |
| MVP | Model-View-Presenter | `references/architectural/mvp.md` |
| CQRS | Separate read and write models | `references/architectural/cqrs.md` |
| Event Sourcing | Store state as sequence of events | `references/architectural/event-sourcing.md` |
| Specification | Composable business rules | `references/architectural/specification.md` |
| Hexagonal | Ports & Adapters — decouple core from I/O | `references/architectural/hexagonal.md` |
| Clean Architecture | Enforce dependency rules between layers | `references/architectural/clean-architecture.md` |
| Microkernel | Core + plugins | `references/architectural/microkernel.md` |
| Layered | Separate concerns into horizontal layers | `references/architectural/layered.md` |
| Pipe and Filter | Transform data through chained stages | `references/architectural/pipe-and-filter.md` |

### Concurrency Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Producer-Consumer | Decouple production from consumption via buffer | `references/concurrency/producer-consumer.md` |
| Read-Write Lock | Many readers or one writer | `references/concurrency/read-write-lock.md` |
| Thread Pool | Reuse a fixed set of worker threads | `references/concurrency/thread-pool.md` |
| Future / Promise | Placeholder for async result | `references/concurrency/future-promise.md` |
| Actor Model | Isolated actors communicating via messages | `references/concurrency/actor-model.md` |
| Reactor | Demultiplex I/O events to handlers | `references/concurrency/reactor.md` |
| Monitor | Mutual exclusion with condition variables | `references/concurrency/monitor.md` |
| Active Object | Decouple method invocation from execution | `references/concurrency/active-object.md` |

### Functional Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Higher-Order Functions | Functions that take/return functions | `references/functional/higher-order-functions.md` |
| Monad | Chain computations that carry context | `references/functional/monad.md` |
| Immutability | Data that cannot be changed after creation | `references/functional/immutability.md` |
| Currying | Transform multi-arg function into chain of single-arg | `references/functional/currying.md` |
| Memoization | Cache function results by arguments | `references/functional/memoization.md` |
| Pattern Matching | Destructure and branch on data shape | `references/functional/pattern-matching.md` |
| Lazy Evaluation | Defer computation until value is needed | `references/functional/lazy-evaluation.md` |

### Resilience Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Circuit Breaker | Stop calling a failing service | `references/resilience/circuit-breaker.md` |
| Retry | Retry with exponential backoff + jitter | `references/resilience/retry.md` |
| Bulkhead | Isolate failures to prevent cascading | `references/resilience/bulkhead.md` |
| Saga | Coordinate distributed transactions | `references/resilience/saga.md` |
| Rate Limiter | Throttle request throughput | `references/resilience/rate-limiter.md` |
| Timeout | Set upper bound on operation duration | `references/resilience/timeout.md` |
| Fallback | Provide degraded functionality on failure | `references/resilience/fallback.md` |

### Data Access Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Active Record | Object wraps a DB row and handles persistence | `references/data-access/active-record.md` |
| Data Mapper | Separate objects that transfer data to/from DB | `references/data-access/data-mapper.md` |
| Identity Map | Cache loaded objects to avoid duplicates | `references/data-access/identity-map.md` |
| Lazy Loading | Load related data on first access | `references/data-access/lazy-loading.md` |
| DTO | Data Transfer Object — cross-boundary data carrier | `references/data-access/dto.md` |
| Value Object | Equality by value content, not identity | `references/data-access/value-object.md` |
| Aggregate | Cluster of domain objects treated as a unit | `references/data-access/aggregate.md` |

### Messaging Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Publish-Subscribe | Broadcast to many subscribers via topics | `references/messaging/publish-subscribe.md` |
| Message Queue | Async decoupling with guaranteed delivery | `references/messaging/message-queue.md` |
| Event Bus | In-process event routing | `references/messaging/event-bus.md` |
| Request-Reply | Send request and wait for correlated response | `references/messaging/request-reply.md` |
| Dead Letter Queue | Route failed messages for inspection | `references/messaging/dead-letter-queue.md` |

### Testing Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Test Doubles | Mock, Stub, Spy, Fake, Dummy | `references/testing/test-doubles.md` |
| Arrange-Act-Assert | Three-phase test structure | `references/testing/arrange-act-assert.md` |
| Given-When-Then | BDD scenario structure | `references/testing/given-when-then.md` |
| Page Object | Encapsulate UI page for testing | `references/testing/page-object.md` |
| Test Data Builder | Fluent construction of test fixtures | `references/testing/test-data-builder.md` |

### Error Handling Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| Guard Clause | Validate inputs at function entry | `references/error-handling/guard-clause.md` |
| Result Type | Return success-or-error instead of throwing | `references/error-handling/result-type.md` |
| Fail-Fast | Detect and report errors immediately | `references/error-handling/fail-fast.md` |
| Exception Hierarchy | Organize exceptions into meaningful tree | `references/error-handling/exception-hierarchy.md` |

### Microservice Patterns
| Pattern | One-line summary | Reference |
|---------|-----------------|-----------|
| API Gateway | Single entry point routing to services | `references/microservice/api-gateway.md` |
| Service Discovery | Dynamic service location | `references/microservice/service-discovery.md` |
| Strangler Fig | Incremental legacy migration | `references/microservice/strangler-fig.md` |
| Sidecar | Attach cross-cutting behavior to a service | `references/microservice/sidecar.md` |
| Backend-for-Frontend | Client-specific API aggregation | `references/microservice/backend-for-frontend.md` |

---

## 📏 Pattern Documentation Format

Every pattern file in this skill follows this structure:

1. **Name and Classification** — Pattern name, category, GoF classification if applicable
2. **Problem** — What problem does this pattern solve?
3. **Solution** — How does the pattern solve it? (one paragraph)
4. **When to Use** — Specific situations where this pattern is the right choice
5. **When to Avoid** — Anti-patterns and situations where this pattern is wrong
6. **Pseudocode** — Language-agnostic implementation showing the structure
7. **Python Implementation** — Tested, runnable Python 3 code
8. **Go Implementation** — Tested, runnable Go code
9. **JavaScript Implementation** — Tested, runnable Node.js code
10. **Related Patterns** — Patterns commonly used together or easily confused

> **Note**: The `🔗 Pattern Synergies` table and all decision trees in this SKILL.md
> are the authoritative source for related-pattern combinations. Each individual
> pattern file may also list its closest related patterns at the end.

---

## 📂 Complete Reference Index

| Category | Files | Patterns Covered |
|----------|-------|-----------------|
| `references/solid-principles/` | 6 | SRP, OCP, LSP, ISP, DIP |
| `references/creational/` | 8 | Factory, Abstract Factory, Builder, Prototype, Singleton, Object Pool, DI |
| `references/structural/` | 9 | Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy, Module |
| `references/behavioral/` | 13 | Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor, Null Object |
| `references/architectural/` | 15 | Repository, Unit of Work, Service Layer, MVC, MVVM, MVP, CQRS, Event Sourcing, Specification, Hexagonal, Clean Architecture, Microkernel, Layered, Pipe and Filter |
| `references/concurrency/` | 9 | Producer-Consumer, Read-Write Lock, Thread Pool, Future/Promise, Actor Model, Reactor, Monitor, Active Object |
| `references/functional/` | 8 | Higher-Order Functions, Monad, Immutability, Currying, Memoization, Pattern Matching, Lazy Evaluation |
| `references/resilience/` | 8 | Circuit Breaker, Retry, Bulkhead, Saga, Rate Limiter, Timeout, Fallback |
| `references/data-access/` | 8 | Active Record, Data Mapper, Identity Map, Lazy Loading, DTO, Value Object, Aggregate |
| `references/messaging/` | 6 | Publish-Subscribe, Message Queue, Event Bus, Request-Reply, Dead Letter Queue |
| `references/testing/` | 6 | Test Doubles, AAA, GWT, Page Object, Test Data Builder |
| `references/error-handling/` | 5 | Guard Clause, Result Type, Fail-Fast, Exception Hierarchy |
| `references/microservice/` | 6 | API Gateway, Service Discovery, Strangler Fig, Sidecar, BFF |
