Design Patterns

Choose, implement, refactor toward, and review the 22 classic Gang-of-Four design patterns. Use when a design problem needs a proven structure (object creation, interface adaptation, composition, tree structures, traversal, state-dependent behavior, decoupling, undo, access control, memory pressure), when comparing similar patterns such as Factory Method vs Abstract Factory, Strategy vs State, or Decorator vs Proxy, when replacing conditionals, inheritance explosions, or tangled dependencies, and when auditing a codebase for missing or over-applied patterns.

O que é Design Patterns?

Design Patterns is a Claude Code agent skill that choose, implement, refactor toward, and review the 22 classic Gang-of-Four design patterns. Use when a design problem needs a proven structure (object creation, interface adaptation, composition, tree structures, traversal, state-dependent behavior, decoupling, undo, access control, memory pressure), when comparing similar patterns such as Factory Method vs Abstract Factory, Strategy vs State, or Decorator vs Proxy, when replacing conditionals, inheritance explosions, or tangled dependencies, and when auditing a codebase for missing or over-applied patterns.

Funciona com✓Claude Code~Codex CLI✓Cursor✓OpenCode
npx skills add https://github.com/libkluid/.skills/tree/main/skills/design-patterns

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que Design Patterns faz?

A working guide to the 22 Gang-of-Four patterns as framed in Dive Into Design Patterns (Alexander Shvets, 2022). It covers three jobs:

  1. Selection — turn a symptom into a shortlist, then a single recommendation.
  2. Implementation / refactoring — apply a pattern without breaking behavior.
  3. Review / diagnosis — find missing structure and, more often, over-applied structure.

The catalog is deliberately language-neutral. Map the roles and steps onto the idioms of the codebase in front of you; do not transliterate Java.

Portability

This skill is self-contained at the directory level. Copying SKILL.md alone is enough.

  • Project-local: <repo>/.opencode/skills/design-patterns/SKILL.md
  • User-global: ~/.config/opencode/skills/design-patterns/SKILL.md
  • Compatible locations: the same structure under <repo>/.claude/skills/ or ~/.agents/skills/
  • The skill ID is the directory name (design-patterns); the frontmatter name is only a display label.

When to use this skill

  • A change keeps rippling through unrelated classes, or a class keeps growing branches for every new case.
  • Object construction has become a wall of parameters, flags, or factories.
  • Integrating a third-party or legacy API that does not match your interfaces.
  • Adding behavior in combinations (compression + encryption + retry + logging) that would explode a subclass hierarchy.
  • Behavior depends on a lifecycle: draft → review → published, connecting → connected → closed, pending → paid → shipped.
  • One change must notify an unknown or changing set of consumers.
  • Operations, undo, queued work, or replayable actions need to become objects.
  • Traversal, export, or analysis must be added over a tree or object graph.
  • Memory pressure comes from many nearly identical objects.
  • Reviewing a design for either spaghetti coupling or speculative abstraction.

When not to use this skill

  • A script, a one-off migration, or a prototype where the cost of structure exceeds its lifetime.
  • The only reason to add a pattern is "best practice", a book, or a linter.
  • You cannot name the concrete change the structure is supposed to absorb.
  • The language already gives the behavior directly (iterators, events, pattern matching, dependency injection, closures).
  • The team cannot maintain the indirection. A simpler design that is understood beats a correct pattern that is not.

Ground rules

  1. A pattern is a name for a structure that emerged, not a target. Recommend the structure; use the pattern name only to explain it.
  2. Three tests before applying a pattern. (a) There is a concrete force or symptom today, not a hypothetical one. (b) At least two plausible variants exist now or are scheduled. (c) The added indirection pays for itself within the next few changes.
  3. Prefer the smallest structure that works: inline code → function → parameterized function → interface + one implementation → interface + multiple implementations → full pattern.
  4. Never add a pattern in review without evidence. Cite the duplication, branch count, dependency edge, or measured cost that justifies it.
  5. Name roles after the domain, not the pattern. ShippingPolicy beats ShippingStrategy; DocumentPublisher beats DocumentObserverSubject unless the pattern itself is the shared vocabulary.
  6. Delete the old path. A pattern applied as a second parallel path with no removal plan is technical debt with extra steps.
  7. Patterns compose. Most real designs are one pattern with another inside it (Composite + Visitor, Command + Memento, Mediator + Observer). Choose the primary force first; let collaborators follow.

0. Establish context first

Do not recommend a pattern before answering these. Ask when the code cannot answer them.

  • Language and paradigm. Inheritance-heavy, interface-based, functional, or mixed? Does it have first-class functions, sum types, pattern matching, generators, events, DI?
  • Change axis. Which dimension actually varies: creation, algorithm, structure, communication, lifecycle, storage, or transport?
  • Variant count. How many implementations exist today? How many are scheduled? ("One now, one next quarter" is a legitimate answer.)
  • Lifecycle and ownership. Who creates, owns, caches, and disposes objects? Is there a composition root or DI container?
  • Concurrency. Are instances shared across threads? Is notification synchronous? Are commands queued?
  • Persistence and distribution. Must objects or events be serialized, versioned, retried, or sent over a network?
  • Performance budget. Is memory, latency, or allocation rate measured and constrained?
  • Test strategy. Can the design be exercised without the real database, clock, filesystem, or network?
  • Team conventions. Does the codebase already use a pattern vocabulary, framework extension points, or architectural boundaries?

Record the answers. A recommendation without this context is a guess.


1. Choosing a pattern

1.1 Symptom → candidates

SymptomFirst candidatesConsider instead
new scattered across business logic; type chosen by configFactory MethodDI container, simple factory function
Several related products must match (same theme, driver, vendor)Abstract FactoryFactory Method per product, parameterized factory
Constructor has many optional parameters or flag argumentsBuilderNamed/optional parameters, record + validation
Copying an object requires knowing its concrete class or private fieldsPrototypeCopy constructor, serialization round-trip
One shared resource needs exactly one instance and global accessSingletonContainer-scoped singleton, module-level instance, explicit injection
Third-party/legacy interface does not fitAdapterChange your interface, anti-corruption layer
Two independent dimensions multiply subclasses (shape × color, device × OS)BridgeSplit into two parameters, composition
Part-whole tree must be treated uniformlyCompositePlain recursive functions over a data model
Behavior combinations explode subclasses (notify by email + SMS + Slack)DecoratorFlags, middleware chain, strategy list
Clients drown in a multi-class subsystemFacadeNarrow module API, service layer
Millions of similar objects exhaust memoryFlyweightInterning, struct-of-arrays, lazy data
Access, lazy loading, caching, or remote calls must be transparentProxyExplicit caching layer, repository, client wrapper
A request may be handled by one of several handlers in unknown orderChain of ResponsibilityMiddleware pipeline, ordered list of functions
Actions must be queued, retried, logged, undone, or parameterizedCommandClosures, job queue payloads, event sourcing
Traversal must be uniform and independent of representationIteratorLanguage iterators/generators
Many components talk to many components; reusable components impossibleMediatorEvent bus, application service, Observer
Undo/rollback must restore state without exposing internalsMementoEvent log, database transaction, copy-on-write snapshot
One change must notify a dynamic set of consumersObserverMessage broker, reactive streams, signals
Large switch on state; transitions scatteredStateState-machine library, transition table, sum types
Multiple algorithms for one task; selection at runtime/configStrategyFunction parameter, table lookup, polymorphism
Same algorithm skeleton, a few steps varyTemplate MethodStrategy/composition, higher-order functions, hooks
Many unrelated operations over a stable object structureVisitorPattern matching, external functions, serializers
Aggregate operations over a treeComposite + VisitorRecursive fold, query API

1.2 Constraint filters

Apply these before the tie-breakers. They eliminate more bad answers than any pattern comparison.

  • Static vs dynamic change. Strategy, State, Bridge, and Proxy allow runtime replacement. Template Method and inheritance-based Factory Method fix behavior at compile time.
  • One object vs a family. Factory Method creates one product; Abstract Factory creates a compatible family; Builder assembles one complex product in steps.
  • Wrap vs replace vs simplify. Decorator keeps the interface and adds behavior; Proxy keeps the interface and controls access; Adapter changes the interface; Facade defines a new, simpler interface over many objects.
  • Push vs pull vs route. Observer broadcasts to all subscribers; Mediator routes interactions through one coordinator; Chain of Responsibility passes a request until someone handles it.
  • State vs algorithm. State objects know each other and trigger transitions; Strategy objects are independent and chosen by the client.
  • Structure vs operation. Composite organizes objects; Visitor adds operations over that organization; Iterator supplies traversal.
  • Memory vs CPU. Flyweight trades CPU and complexity for RAM; Proxy caching trades freshness and latency for repeated work.
  • Process boundary. Remote Proxy, Command serialization, and Observer across processes add failure modes (retries, ordering, idempotency) that in-process patterns do not have.

1.3 Head-to-head tie-breakers

PairChoose the first whenChoose the second when
Factory Method / Abstract FactoryOne product type; subclasses or config pick the concrete classSeveral related products must be created and stay compatible
Abstract Factory / BuilderProducts are returned immediately as a familyOne complex product is assembled in steps and returned at the end
Factory Method / BuilderThe variation is which class is createdThe variation is how a complex object is configured
Builder / PrototypeConstruction must be validated step by stepA fully configured object already exists and should be copied
Adapter / BridgeRetrofitting incompatible code after the factDesigning two independent hierarchies up front
Adapter / FacadeOne interface must be translated to anotherMany subsystem calls must be collapsed into one simple API
Decorator / ProxyAdd or remove responsibilities at runtime; client composes wrappersControl access, lifetime, caching, or remoteness; proxy manages the service
Decorator / Chain of ResponsibilityEvery wrapper runs and adds behaviorA handler may stop the chain
Composite / DecoratorThe goal is a tree with uniform leaf/container operationsThe goal is extra responsibility on a node, not aggregation
Facade / MediatorOne-way simplification; subsystem does not know the facadeTwo-way coordination; colleagues know and call the mediator
Mediator / ObserverCentral coordination logic and star topologyOne-to-many broadcast with no central policy
Strategy / StateAlgorithms are independent; client switchesStates trigger their own transitions and depend on each other
Strategy / CommandThe question is how to perform one taskThe question is what request to perform, store, or undo
Strategy / Template MethodBehavior varies per object at runtime via compositionBehavior varies per subclass at compile time via inheritance
Chain of Responsibility / ObserverExactly one handler should actAll subscribers should be notified
Memento / CommandThe requirement is state restorationThe requirement is request encapsulation, queueing, or replay
Memento / PrototypeEncapsulation must be preserved and history is neededA simple copy of a simple object is enough
Iterator / VisitorThe requirement is traversal order and accessThe requirement is an operation across many element types
Visitor / StrategyMany operations over a stable element hierarchyOne interchangeable algorithm over a context
Flyweight / SingletonMany immutable shared instances keyed by stateExactly one mutable instance for the whole process
Composite / FlyweightThe hierarchy and uniform operations matterShared leaf state is the memory problem

1.4 Decision tree

What is the primary force?
├─ Creating objects
│  ├─ Which concrete class is chosen by subclass/config?        → Factory Method
│  ├─ Several related products must match?                      → Abstract Factory
│  ├─ One complex object, many optional parts or steps?         → Builder
│  └─ Copy an existing configured object?                       → Prototype
│     └─ Truly one shared instance?                             → Singleton (last resort)
├─ Adapting or organizing structure
│  ├─ Incompatible interface from outside your control?         → Adapter
│  ├─ Two independent dimensions multiply subclasses?           → Bridge
│  ├─ Part-whole tree with uniform operations?                  → Composite
│  ├─ Add/remove behavior in combinations at runtime?           → Decorator
│  ├─ Simplify a complex subsystem for clients?                 → Facade
│  ├─ Too many near-identical objects in memory?                → Flyweight
│  └─ Control access, lifetime, caching, or remoteness?         → Proxy
└─ Behavior and communication
   ├─ One of several handlers, order unknown?                   → Chain of Responsibility
   ├─ Requests must be objects: queue, retry, undo, replay?     → Command
   ├─ Traverse without exposing representation?                 → Iterator
   ├─ Many-to-many communication needs a coordinator?           → Mediator
   ├─ Restore prior state without breaking encapsulation?       → Memento
   ├─ Notify a dynamic set of subscribers?                      → Observer
   ├─ Behavior changes with lifecycle state?                    → State
   ├─ Interchangeable algorithms chosen at runtime?             → Strategy
   ├─ Fixed algorithm skeleton, varying steps?                  → Template Method
   └─ Many operations over a stable object structure?           → Visitor

1.5 When the answer is "no pattern"

Recommend one of these instead, and say why:

  • Extract a function or module. One behavior, one call site, no variants.
  • Pass a parameter. A boolean or enum is honest when there are exactly two stable cases and no plan for more.
  • Use the language. Generators for traversal, closures for callbacks, events/signals for notification, DI for lifecycle, sealed unions and pattern matching for state or operations.
  • Fix the boundary. Many "pattern" problems are really a missing module boundary, a leaking framework type, or a god service.
  • Measure first. Flyweight, Proxy caching, and lazy loading are performance decisions; without a profile they are speculation.
  • Wait for the second variant. Keep the code direct and add a seam (an interface or function parameter) where the variant will enter.

2. Pattern catalog

2.1 At a glance

PatternIntent in one lineReach for it whenMain cost
Factory MethodSubclasses decide which product class to instantiateCreation type varies by config/subclassNew subclass per product
Abstract FactoryCreate compatible families without concrete classesMultiple products must match by variantAdding a product kind touches every factory
BuilderAssemble a complex object step by stepMany optional parts; validation at the endBuilder classes plus optional director
PrototypeClone without coupling to concrete classesConfigured objects should be copiedDeep-copy and identity hazards
SingletonOne instance, global accessA truly single shared resourceHidden dependency; test and concurrency pain
AdapterTranslate one interface into anotherThird-party or legacy incompatibilityExtra layer; leaky translations
BridgeSeparate abstraction from implementationTwo independent dimensions varyInvented second dimension becomes overhead
CompositeTreat leaves and containers uniformlyPart-whole treesOver-general component interface
DecoratorWrap to add responsibilities at runtimeCombinable behaviorsWrapper stacks and ordering
FacadeOne simple API over a subsystemClients drown in subsystem detailsGod-object risk
FlyweightShare immutable state across many objectsMemory-bound near-duplicatesCPU and complexity; immutability required
ProxySurrogate controlling accessLazy load, secure, cache, remoteLatency and lifecycle complexity
Chain of ResponsibilityPass a request until handledUnknown handler order/setRequests can fall through
CommandEncapsulate a request as an objectQueue, retry, undo, replayClass per action; history memory
IteratorTraverse without exposing structureUniform or multiple traversalsInvalidation and snapshot semantics
MediatorCentralize colleague communicationMany-to-many interactionsMediator becomes a god object
MementoSnapshot and restore stateUndo, rollback, checkpointsMemory; retention policy
ObserverNotify subscribers of changesDynamic one-to-many eventsOrdering, leaks, reentrancy
StateBehavior follows internal stateLifecycle with many transitionsState class sprawl; transition ownership
StrategySwap algorithms via compositionRuntime algorithm choiceClient must understand variants
Template MethodBase class fixes the skeletonSame flow, varying stepsFragile inheritance; LSP risk
VisitorOperations separate from structureMany operations, stable elementsAdding element types breaks visitors

2.2 Creational patterns

Factory Method · creational · book p.74–89

Intent. Define an interface for creating a product, but let subclasses (or a configured creator) decide which concrete product to instantiate.

Use when. The exact type or dependency is unknown until runtime; a library needs an extension point for internal components; products should be reused rather than rebuilt; callers must not know concrete classes.

Roles. Product (common interface), ConcreteProduct, Creator (declares the factory method and holds core logic), ConcreteCreator (overrides creation).

Steps.

  1. Unify all products behind one interface.
  2. Declare a factory method on the creator returning that interface.
  3. Replace direct new calls in creator logic with the factory call.
  4. Add one creator subclass per product and override the factory method.

Pitfalls. A static helper that returns a hard-coded type is not this pattern. The creator still owns business logic; it is not a "factory class". Subclass explosion is real when products vary by data rather than by type — a parameter or registry may be better.

Neighbors. Often the first step toward Abstract Factory, Builder, or Prototype. Frequently one step inside Template Method. Abstract Factory is usually a set of factory methods.

Abstract Factory · creational · book p.90–104

Intent. Create families of related products without naming concrete classes, so products from one variant are always compatible.

Use when. The system must be independent of how products are created; several product families exist (theme, vendor, driver, platform); a configuration or environment selects the whole family.

Roles. AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct, Client.

Steps.

  1. Map product kinds × variants.
  2. Declare an interface per product kind.
  3. Declare one creation method per product kind on the abstract factory.
  4. Implement one factory per variant.
  5. Select the factory once, at startup or in a composition root.

Pitfalls. Adding a new product kind changes the factory interface and every concrete factory. This pattern fits stable product kinds with growing variants, not the reverse. It also hides the concrete classes so well that debugging requires tracing factory selection.

Neighbors. Composed of factory methods. Builder assembles one complex product instead of a family. Facade may use a factory to hide subsystem construction.

Builder · creational · book p.105–123

Intent. Construct a complex object step by step so the same process can produce different representations.

Use when. Constructors telescope into many optional parameters; the object must be validated only when complete; the same assembly process yields different representations; a composite tree must be assembled recursively.

Roles. Builder (step interface), ConcreteBuilder, Product, Director (optional, fixes step order), Client.

Steps.

  1. Identify the steps shared by all representations.
  2. Declare them on the builder interface.
  3. Implement a concrete builder per representation; expose the result at the end.
  4. Add a director only if several clients repeat the same step sequence.
  5. Validate in build()/getResult(), not in each setter.

Pitfalls. A fluent setter chain is a convenient API, not necessarily the GoF pattern; that is fine, but do not claim more structure than exists. Reusing a builder requires an explicit reset(). Returning a half-built product breaks the invariant the builder was meant to protect.

Neighbors. Abstract Factory returns products immediately; Builder defers. Useful for Composite trees. A director can be the abstraction side of a Bridge.

Prototype · creational · book p.124–137

Intent. Copy existing objects without coupling the client to their concrete classes.

Use when. The class to copy is unknown at compile time; construction is more expensive than copying; many subclasses differ only in initial configuration and can be replaced by preconfigured prototypes; a registry of templates is useful.

Roles. Prototype (clone interface), ConcretePrototype, Prototype Registry (optional).

Steps.

  1. Declare a clone method on the prototype interface.
  2. Implement a copy constructor that takes the source object.
  3. Clone by constructing a new instance from this.
  4. Copy owned mutable fields deeply; share only immutable data.
  5. Add a registry only if prototypes are looked up by key.

Pitfalls. Shallow copies silently share mutable state. Cycles, caches, locks, connections, and listeners need explicit handling. Copy constructors are usually safer than language clone APIs. Decide whether identity and IDs are copied.

Neighbors. An alternative to Memento when state is simple. Useful for snapshotting Composite trees and duplicating Commands in history.

Singleton · creational · book p.138–146

Intent. Guarantee one instance and provide a controlled access point.

Use when. A resource genuinely must be single per process (or per defined scope), and its lifecycle cannot be owned by a container or composition root.

Roles. Singleton: private constructor, static instance field, static accessor.

Steps.

  1. Make the constructor private (or otherwise prevent external construction).
  2. Store the instance in a private static field.
  3. Expose a static accessor with lazy or eager initialization.
  4. Make initialization thread-safe if the runtime is concurrent.
  5. Prefer registering the same instance in a DI container over a static accessor.

Pitfalls. It violates SRP by combining uniqueness with business behavior. It hides dependencies, complicates tests, and creates global mutable state. Concurrency, serialization/deserialization, reflection, multiple class loaders, and multiple processes all break naive implementations. "One instance per container/tenant/request" is not this pattern.

Neighbors. Facades are often made singletons. Abstract Factory, Builder, and Prototype instances can be singletons. Prefer dependency injection for lifecycle.

2.3 Structural patterns

Adapter · structural · book p.150–163

Intent. Let objects with incompatible interfaces collaborate by translating one interface into another.

Use when. Integrating a third-party or legacy API; unifying several similar APIs behind your own port; migrating incrementally without rewriting callers.

Roles. Client, Client Interface/Target, Service/Adaptee, Adapter. A class adapter inherits both sides where multiple inheritance exists; an object adapter wraps the service by composition.

Steps.

  1. Define the interface the client needs (the target).
  2. Implement an adapter that holds or inherits the service.
  3. Translate parameters, return values, errors, and naming in the adapter.
  4. Inject the adapter at the boundary; keep business logic out of it.

Pitfalls. Leaky translations expose vendor types. Business rules creep into the adapter. Many adapters over time signal a missing canonical domain model. Two-way adapters are usually a sign to pick one interface.

Neighbors. Bridge separates hierarchies by design; Adapter retrofits them. Decorator and Proxy keep the interface; Adapter changes it. Facade simplifies many objects rather than translating one.

Bridge · structural · book p.164–178

Intent. Split a large class or cluster into abstraction and implementation hierarchies that vary independently.

Use when. Two orthogonal dimensions multiply subclasses (shape × color, remote × device, domain × transport); implementations must be swappable at runtime; platform-specific code should not leak into policy code.

Roles. Abstraction (high-level policy, holds an implementation reference), RefinedAbstraction, Implementation (common interface), ConcreteImplementation, Client.

Steps.

  1. Identify the two axes that vary independently.
  2. Put one axis in the abstraction hierarchy and the other behind an interface.
  3. Hold the implementation by composition, not inheritance.
  4. Let clients supply the implementation at construction.

Pitfalls. Do not invent a second dimension that has only one implementation. If the abstraction must expose implementation details, the split is wrong. This is a design-time decision; applying it late can be expensive.

Neighbors. Adapter connects existing incompatible code; Bridge prevents the incompatibility up front. Abstract Factory can create implementations. Strategy also delegates, but its purpose is interchangeable algorithms rather than two evolving hierarchies.

Composite · structural · book p.179–192

Intent. Compose objects into trees and treat individual leaves and containers uniformly.

Use when. The domain is a part-whole hierarchy (files, UI widgets, org units, expressions); clients should not branch on "leaf vs container"; aggregates must be computed recursively.

Roles. Component (common operations), Leaf, Composite (children plus delegation), Client.

Steps.

  1. Define the component interface shared by leaves and containers.
  2. Implement leaves with the primitive behavior.
  3. Implement containers holding child components and delegating/aggregating.
  4. Decide where add/remove live (see pitfalls).
  5. Guard against cycles and define empty-container semantics.

Pitfalls. Forcing unrelated classes behind one interface over-generalizes it. Putting child management on the component maximizes transparency but gives leaves meaningless methods; putting it only on composites is safer but requires type checks. Parent references create cycles. Cached aggregates need invalidation.

Neighbors. Builder can assemble the tree. Decorator adds responsibility rather than aggregating children. Flyweight can share leaves. Chain of Responsibility can bubble requests to parents. Visitor adds operations; Iterator supplies traversal.

Decorator · structural · book p.193–210

Intent. Attach additional responsibilities to an object at runtime by wrapping it in objects that share its interface.

Use when. Behaviors combine orthogonally (compression, encryption, logging, retry); responsibilities must be added or removed dynamically; subclassing would explode; the target class is final or third-party.

Roles. Component, ConcreteComponent, BaseDecorator (holds a component and delegates), ConcreteDecorator, Client.

Steps.

  1. Define the component interface shared by the target and wrappers.
  2. Implement the base decorator with a component field and pure delegation.
  3. Add concrete decorators that run logic before/after delegation.
  4. Let the client stack decorators in the required order.
  5. Provide a builder or factory if stack construction is complex.

Pitfalls. Wrapper stacks are hard to debug; order can change behavior; removing a specific wrapper is awkward; identity/equality comparisons break. Decorators must not change the interface (that is Adapter). Language annotations named "decorator" are unrelated.

Neighbors. Proxy keeps the interface but controls access and lifecycle. Chain of Responsibility may stop; Decorator always forwards and accumulates. Composite aggregates children; Decorator wraps one. Strategy swaps one behavior; Decorator stacks several.

Facade · structural · book p.211–220

Intent. Provide a simplified, stable interface to a library, framework, or complex subsystem.

Use when. Clients need one task but must wire many classes; a subsystem is hard to use correctly; you want a stable entry point across versions or layers.

Roles. Facade, Additional Facades (optional), Subsystem Classes, Client.

Steps.

  1. Identify the few operations clients actually need.
  2. Implement them in a facade that orchestrates the subsystem.
  3. Move clients to the facade; keep the subsystem usable directly.
  4. Split the facade if it accumulates unrelated responsibilities.

Pitfalls. The facade becomes a god object or a second domain model. It hides capabilities clients legitimately need, so they bypass it and the abstraction rots. It is a convenience, not an access-control boundary.

Neighbors. Adapter translates one interface; Facade defines a new one over many. Mediator coordinates two-way communication; Facade is one-way. Abstract Factory can hide subsystem creation. Facades are often singletons, which adds coupling.

Flyweight · structural · book p.221–234

Intent. Share immutable intrinsic state across many objects so more objects fit in memory.

Use when. There are huge numbers of similar objects; most state is identical and immutable; memory is a measured bottleneck; per-object identity is not required.

Roles. Flyweight (immutable shared state), Context (extrinsic state plus a flyweight reference), Flyweight Factory (pool/cache), Client.

Steps.

  1. Split fields into intrinsic (shared, immutable) and extrinsic (per-instance).
  2. Make the flyweight immutable; initialize via constructor only.
  3. Pass extrinsic state into operations instead of storing it in the flyweight.
  4. Add a factory keyed by intrinsic state; return existing instances.
  5. Bound the pool; define eviction if the key space is unbounded.

Pitfalls. A mutable flyweight corrupts every context that shares it. An unbounded pool becomes a leak. The pattern trades CPU for RAM; without a profile the complexity may be wasted. Do not assume object identity is preserved.

Neighbors. Singleton is one mutable instance; Flyweight is many immutable instances. Composite trees can share leaf flyweights. Caching Proxy stores results, not shared object state.

Proxy · structural · book p.235–246

Intent. Provide a surrogate or placeholder that controls access to another object.

Use when. Lazy-initialize an expensive object; enforce access control; hide remoteness; add logging, metrics, or caching; implement copy-on-write or reference counting.

Roles. Service Interface, Service, Proxy (holds a service reference), Client.

Steps.

  1. Extract or confirm the service interface.
  2. Implement the proxy against the same interface.
  3. Hold or create the real service inside the proxy.
  4. Intercept calls for the specific concern, then delegate.
  5. Define lifecycle and failure behavior explicitly.

Pitfalls. Indirection adds latency and debugging cost. Interface drift between proxy and service breaks substitutability. Lazy proxies must handle concurrent initialization and failure. A proxy that adds behavior chosen by the client is a Decorator; a proxy that changes the interface is an Adapter.

Neighbors. Decorator adds responsibilities, with the client composing the stack. Adapter changes the interface. Facade simplifies many objects. Remote proxies add network failure modes that in-process patterns do not have.

2.4 Behavioral patterns

Chain of Responsibility · behavioral · book p.251–268

Intent. Pass a request along a chain of handlers until one handles it or the chain ends.

Use when. Several handlers may process a request and the set/order is not known up front; middleware pipelines; UI event bubbling; approval workflows; runtime-configurable processing stages.

Roles. Handler, BaseHandler (optional next-link plumbing), ConcreteHandler, Client.

Steps.

  1. Declare a handler interface with the handling operation.
  2. Optionally add a base handler holding the next link.
  3. Implement handlers that decide to handle, stop, or forward.
  4. Assemble the chain in one place; define a terminal handler or fallback.
  5. Make the unhandled case explicit (error, default, or no-op with logging).

Pitfalls. Requests silently fall through. Cycles or misordered links hang or skip logic. Implicit control flow is hard to trace. Dynamic chains need validation and observability. Async chains need cancellation and timeout rules.

Neighbors. Decorator always forwards and accumulates behavior. Observer notifies everyone. Composite can bubble requests to a parent. Command turns each request into an object before it enters the chain.

Command · behavioral · book p.269–289

Intent. Encapsulate a request as an object containing everything needed to perform it, enabling parameterization, queueing, logging, and undo.

Use when. UI actions must be bound dynamically; work must be queued, scheduled, retried, or sent remotely; operations need undo/redo; macros combine commands; audit trails are required.

Roles. Invoker/Sender, Command, ConcreteCommand, Receiver, Client.

Steps.

  1. Declare a command interface with a minimal execution method.
  2. Implement one command per request, storing receiver and arguments.
  3. Make the invoker hold and trigger commands without knowing their details.
  4. Add undo only if the command can reverse its effects correctly.
  5. Store executed commands in a bounded history.

Pitfalls. One class per action can explode; closures may be enough. Undo requires capturing prior state (often with Memento) and handling side effects. Retries require idempotency. Serialized commands need versioning. History grows unbounded unless trimmed.

Neighbors. Pair with Memento for undo. Strategy chooses how; Command represents what. Composite builds macros. Prototype duplicates commands. Observer can trigger command execution.

Iterator · behavioral · book p.290–304

Intent. Traverse a collection without exposing its internal representation.

Use when. Multiple traversal orders are needed; collections differ but must be traversed uniformly; traversal should be lazy or resumable; clients should not depend on storage details.

Roles. Iterator, ConcreteIterator (cursor state), IterableCollection, ConcreteCollection.

Steps.

  1. Declare next/hasNext (or the language equivalent).
  2. Declare a factory method on the collection returning an iterator.
  3. Implement a concrete iterator holding the collection reference and cursor.
  4. Decide between live iteration and snapshot iteration.
  5. Define behavior for concurrent modification.

Pitfalls. Mutation during iteration causes skipped or duplicated elements. Snapshotting large collections is expensive. Iterators can leak resources or hold references. Fail-fast behavior must be documented. Built-in iterators make a hand-rolled implementation unnecessary in most languages.

Neighbors. Composite trees need traversal. Factory Method can create iterators. Visitor applies operations during traversal. Memento can snapshot a collection for stable iteration.

Mediator · behavioral · book p.305–320

Intent. Restrict direct communication between objects and route it through a mediator, reducing many-to-many coupling.

Use when. Components interact in complex ways; UI controls depend on each other; components should be reusable outside their current screen; workflow coordination is scattered across participants.

Roles. Mediator, ConcreteMediator (holds colleagues and coordination logic), Component/Colleague (knows only the mediator).

Steps.

  1. Identify the tightly coupled group and the interactions to centralize.
  2. Declare a mediator notification interface.
  3. Implement the mediator with references to the colleagues.
  4. Replace direct colleague-to-colleague calls with mediator notifications.
  5. Split the mediator when it gains unrelated responsibilities.

Pitfalls. The mediator becomes a god object and a new single point of change. Control flow becomes indirect. Synchronous mediators can deadlock or cascade. Over time, coordination logic may belong in a domain service or event bus.

Neighbors. Observer is a common implementation mechanism (mediator subscribes to colleagues). Facade simplifies one-way access; Mediator coordinates both ways. Chain of Responsibility is sequential; Mediator is centralized.

Memento · behavioral · book p.321–336

Intent. Capture and restore an object's state without exposing its internals.

Use when. Undo/redo, rollback, checkpoints, transaction-like behavior, or debug snapshots are required and encapsulation must be preserved.

Roles. Originator (creates/restores mementos), Memento (immutable snapshot), Caretaker (stores history, cannot inspect contents).

Steps.

  1. Decide what constitutes the originator's state.
  2. Create an immutable memento type holding that state.
  3. Add save() and restore(memento) to the originator.
  4. Restrict memento access to the originator (nested class, friend, module privacy, or an opaque token).
  5. Let a caretaker manage a bounded history with an eviction policy.

Pitfalls. Snapshots can consume large amounts of memory. Deep vs shallow copy must be explicit. Exposing getters breaks the encapsulation the pattern exists to protect. Persisted mementos need schema versioning. Long-lived caretakers leak references.

Neighbors. Command + Memento is the standard undo design. Prototype is a simpler alternative for small object graphs. Event logs may replace snapshots when replay is cheaper than storage.

Observer · behavioral · book p.337–352

Intent. Define a subscription mechanism so one publisher notifies many subscribers when its state changes.

Use when. One change must trigger reactions in an unknown or changing set of objects; UI must react to model changes; domain events decouple producers from consumers.

Roles. Publisher/Subject (subscription list and notification), Subscriber (update interface), ConcreteSubscriber, Client.

Steps.

  1. Split the independent state owner from the dependent reactions.
  2. Declare a subscriber interface with the notification payload.
  3. Add subscribe/unsubscribe to the publisher.
  4. Notify all subscribers on the relevant state change.
  5. Define unsubscribe semantics and error isolation.

Pitfalls. Notification order is unspecified; do not depend on it. Forgetting to unsubscribe leaks subscribers. A throwing subscriber can abort the rest unless isolated. Reentrant updates cause storms or infinite loops. Delivery may be sync or async; mixing them hides failures. Event payloads need versioning across processes.

Neighbors. Mediator often uses Observer internally. Chain of Responsibility stops at one handler; Observer broadcasts. Command can be the notification payload. Message brokers generalize Observer across processes with delivery guarantees.

State · behavioral · book p.353–368

Intent. Let an object change behavior when its internal state changes, as if it changed class.

Use when. Behavior depends on lifecycle state; large switch/if blocks repeat across methods; transitions are explicit; state-specific data or rules exist.

Roles. Context (holds current state, delegates), State (interface), ConcreteState (behavior and optionally transitions).

Steps.

  1. Declare the operations that vary by state.
  2. Implement one state class per state.
  3. Give the context a state reference and delegate to it.
  4. Decide whether the context or the state owns transitions.
  5. Make illegal transitions explicit (ignore, error, or guard).

Pitfalls. Transition ownership becomes ambiguous. Creating state objects per call wastes allocations; share immutable states or cache them. Persisting state requires stable identifiers. Two booleans are not a state machine. The number of states can explode if state is really a combination of independent flags.

Neighbors. Structurally similar to Strategy, but states know and trigger each other. Bridge separates hierarchy dimensions. Prefer a state-machine library or sum types when transitions are data, not behavior.

Strategy · behavioral · book p.369–381

Intent. Define a family of algorithms, encapsulate each, and make them interchangeable at runtime.

Use when. Several algorithms solve one task; selection is runtime or configuration-driven; a volatile algorithm should be isolated from stable context; conditionals choose behavior; variants need independent tests.

Roles. Context, Strategy, ConcreteStrategy, Client.

Steps.

  1. Identify the algorithm that varies and its inputs/outputs.
  2. Declare a strategy interface for that algorithm.
  3. Extract each variant into a concrete strategy.
  4. Give the context a strategy reference and a way to replace it.
  5. Select the strategy at the composition root, not deep inside the context.

Pitfalls. The client must understand variant differences to choose one. Strategies that need many context internals force a god context or wide parameter lists. Stateless strategies are easier to share. A single stable algorithm does not need an interface. Closures may replace the classes entirely.

Neighbors. State has the same shape but interdependent states. Command encapsulates requests, not algorithms. Template Method varies behavior through inheritance; Strategy through composition. Bridge separates two hierarchies; Strategy swaps one behavior.

Template Method · behavioral · book p.382–393

Intent. Define an algorithm's skeleton in a base class and let subclasses override specific steps without changing the order.

Use when. Several classes share a flow but differ in a few steps; duplicated boilerplate should move to a base class; a framework must enforce ordering or invariants; hooks are needed at fixed points.

Roles. AbstractClass (template method plus primitive steps/hooks), ConcreteClass.

Steps.

  1. Decompose the algorithm into steps.
  2. Implement the template method and make it non-overridable.
  3. Declare varying steps as abstract; give stable steps default behavior.
  4. Add empty hooks only where subclasses legitimately need optional extension.
  5. Keep the number of steps small and documented.

Pitfalls. Inheritance locks the design; runtime replacement is impossible. Subclasses can violate invariants or LSP. Protected members become a de facto API. Too many steps make the skeleton unreadable. Composition with Strategy is usually better when variants combine.

Neighbors. Factory Method is a natural step inside a template method. Strategy achieves variation by composition. Bridge addresses two independent hierarchies.

Visitor · behavioral · book p.394–409

Intent. Separate operations from the object structure they operate on, adding new operations without changing element classes.

Use when. Many unrelated operations apply to a stable set of element types; element classes are polluted by export, analysis, or rendering code; results must accumulate across a complex structure.

Roles. Visitor (one visit method per element type), ConcreteVisitor, Element (accept), ConcreteElement, ObjectStructure/Client.

Steps.

  1. Declare a visit method per concrete element type.
  2. Add accept(visitor) to the element interface.
  3. Implement accept as visitor.visit(this) in each element.
  4. Implement one concrete visitor per operation.
  5. Walk the structure (often with Iterator/Composite) and call accept.

Pitfalls. Adding an element type requires changing every visitor. Visitors may lack access to private element state, forcing getters. Traversal responsibility must be assigned explicitly. Cyclic graphs need visited sets. In languages with pattern matching or multiple dispatch, the accept/double-dispatch ceremony may be unnecessary.

Neighbors. Composite provides the structure; Iterator provides traversal. Strategy encapsulates one algorithm in an interchangeable object; Visitor groups many operations over many element types. Command can turn each visit into a request.


3. Implementation and refactoring playbook

3.1 Universal sequence

  1. Pin current behavior. Add characterization tests around the code path, including error cases and side effects. If tests are impossible, record concrete inputs/outputs first.
  2. Name the force. Write one sentence: "Creation type varies by tenant", "notification channels combine arbitrarily", "the parser's state transitions are duplicated in three methods".
  3. Introduce the smallest seam. Usually an interface at the boundary, a constructor parameter, or a function parameter. Do not add the whole pattern yet.
  4. Move one responsibility at a time. Extract the varying code; leave stable code in place. Keep commits small and behavior-preserving.
  5. Wire at the composition root. Choose concrete implementations at startup, configuration, or request boundary — never deep inside domain logic.
  6. Delete the replaced path. Remove dead branches, old constructors, and feature flags once parity is proven.
  7. Add variant tests. One test per implementation, plus interaction tests for ordering, delegation, notification, and undo.
  8. Record the decision. A short note: force, chosen structure, alternatives, cost, and the condition that would justify revisiting.

3.2 Refactoring moves

Current smellFirst movePattern candidateCaution
new ConcreteX() in domain logicExtract creation to one functionFactory MethodDo not create a class per type if a registry suffices
Same switch selecting product familyGroup constructors behind one interfaceAbstract FactoryNew product kinds will break the interface
Constructor with 10 optional parametersIntroduce a parameter objectBuilderValidate at build time; avoid mutable half-built objects
Copying fields from outside the classAdd a copy constructorPrototypeHandle deep copies and identity explicitly
Global getInstance() calls everywhereInject the dependencySingleton (remove it)Prefer container scope; keep a module-level instance only if needed
Vendor type leaking through the appDefine a port; wrap the vendorAdapterKeep translation free of business rules
if (shape == CIRCLE && color == RED) combinationsSplit the two dimensionsBridgeOnly if both dimensions truly vary
instanceof/type checks over a treeAdd a common component interfaceCompositeDecide transparency vs safety for child operations
Subclass per feature combinationWrap the base objectDecoratorWatch order, identity, and stack construction
Client orchestrates five subsystem classesAdd one entry-point functionFacadeDo not hide operations clients still need
Millions of duplicate value objectsExtract immutable shared stateFlyweightMeasure memory first; bound the cache
Expensive object constructed eagerlyAdd a lazy wrapperProxyHandle concurrent init and failure
Nested validation/authorization blocksExtract handlers into a listChain of ResponsibilityDefine the unhandled terminal case
UI callbacks call business methods directlyTurn each action into an objectCommandUse closures if undo/queueing is not required
Custom traversal duplicated in clientsMove cursor state into an iteratorIteratorUse language iterators when available
UI controls reference each otherRoute events through a coordinatorMediatorSplit before it becomes a god object
Undo implemented by public state fieldsAdd an opaque snapshot typeMementoBound history; version persisted snapshots
Model calls every dependent directlyAdd subscribe/notifyObserverDefine unsubscribe and error isolation
Large switch on status in many methodsMove behavior into state classesStateDecide who owns transitions
Runtime if chooses among algorithmsExtract algorithm interfaceStrategyDo not wrap one stable algorithm
Copy-pasted algorithm with small differencesPull the skeleton into a base classTemplate MethodWatch LSP and step count
Export/report methods on every model classMove operations into a visitorVisitorAdding element types becomes expensive

3.3 Language shortcuts

Use the idiom before the ceremony. The pattern's intent matters, not its class diagram.

Language capabilityReplaces or simplifies
First-class functions, closuresStrategy, Command (without undo), Chain of Responsibility, Observer callbacks
Built-in iterators/generatorsIterator
Events, signals, reactive streamsObserver
Sum types, sealed hierarchies, pattern matchingState, Visitor, Command classification
Dependency injection / containersSingleton lifecycle, factory wiring, Abstract Factory selection
Immutable records, copy constructors, with-style updatesPrototype, Builder for data objects
Modules/packages with explicit exportsFacade
Middleware pipelinesChain of Responsibility, Decorator
Interning/pools in the runtimeFlyweight

State the trade-off when choosing a shortcut: closures are harder to serialize and inspect; pattern matching centralizes operations but scatters element behavior; DI hides wiring but makes runtime composition less obvious.

3.4 Testing the result

  • Creational: creation matrix per variant; no concrete type leaks into clients; invalid configurations fail at a defined point; builders reset correctly; prototypes do not share mutable state.
  • Structural: delegation order; wrapper stack behavior; proxy failure and lazy-init paths; composite recursion with empty and deep trees; adapter translation of errors and edge values.
  • Behavioral: handler fall-through; command undo/redo round-trips; iterator behavior under mutation; mediator routing; memento restore equality; observer subscribe/unsubscribe and exception isolation; state transition table; strategy equivalence on shared fixtures; template hook defaults; visitor coverage of every element type.

3.5 Rollout

  • Keep the old API as a thin adapter until callers migrate.
  • Prefer adding the new structure beside the old one, switching one call site at a time.
  • Avoid mixing a refactor with behavior changes in the same commit.
  • Remove the flag and the old path in a follow-up within the same delivery cycle.
  • If the pattern crosses a process boundary, define idempotency, ordering, and retry semantics before shipping.

4. Review and diagnosis

4.1 Missing structure — signals

SignalEvidence to look forLikely direction
Shotgun surgeryOne change edits many unrelated filesMissing boundary; Facade/Mediator or a module split
Repeated type dispatchinstanceof, switch on type in several placesComposite/Visitor or polymorphism
Constructor painMany optional args, booleans, nullsBuilder or parameter object
Creation couplingDomain code names concrete infrastructureFactory Method/Abstract Factory + DI
Subclass explosionClass names encode combinationsBridge, Decorator, or Strategy
Global accessStatic singletons reached from everywhereInjection, scoped lifetime
Tangled UI/modelControls call each other and the modelMediator + Observer
Duplicated traversalCursor logic copied into clientsIterator
Manual undoAd-hoc state copies and restore codeCommand + Memento
Repeated vendor glueSame translation in many call sitesAdapter at one boundary
Memory growthMany near-identical objectsFlyweight after profiling
Latency from eager workExpensive setup on every pathProxy/lazy initialization

4.2 Over-applied structure — signals

Score one point per item. Two or more is a review finding; four or more usually justifies removal.

  • An interface has exactly one implementation and no scheduled second one.
  • A factory creates exactly one product type and is called from one place.
  • Pattern names appear in class names without adding shared vocabulary.
  • A wrapper delegates every method unchanged and adds nothing.
  • A "strategy" is selected once at startup and never changes.
  • A "state" machine has two states and one boolean's worth of behavior.
  • An event/observer layer exists for a single known consumer.
  • A builder wraps a constructor with three parameters.
  • A facade only forwards calls one-to-one.
  • A visitor has one visitor and one element type.
  • Indirection exists "for future flexibility" with no named future change.
  • Tests must mock three layers to exercise one behavior.

4.3 Review questions

Creational. Who owns the lifecycle? Can a test substitute the product? Does the factory hide a concrete dependency that callers still need? Is the object validated before use?

Structural. Does the wrapper preserve substitutability? Is the added layer observable in behavior? Can the stack be constructed and torn down predictably? Does the facade hide a capability the client legitimately needs?

Behavioral. Is the order of handlers/subscribers defined? What happens when nobody handles the request? Can undo be applied twice safely? Are transitions total, or can the system get stuck? Are subscriptions released? Is the mediator accumulating policy that belongs elsewhere?

Cross-cutting. Is the pattern at a boundary or in the domain core? Does it cross a process boundary? Is the indirection measured against a real cost? Would a language feature or a simpler function do the same job?

4.4 Finding template

### <severity>: <short title>

- **Location:** path/to/file.ext:line
- **Symptom:** what repeats, branches, leaks, or blocks change
- **Evidence:** counts, duplicated blocks, dependency edges, profile data
- **Impact:** change cost, test difficulty, runtime risk
- **Recommendation:** the smallest structural move that addresses the force
- **Pattern (optional):** name only as shorthand for the recommended structure
- **Cost / risk:** new indirection, migration steps, rollout concerns
- **Alternative considered:** simpler option and why it is insufficient
- **Revisit trigger:** the change or measurement that would justify more structure

Severity:

  • High: correctness, data loss, or a change that cannot be made safely.
  • Medium: repeated change cost, test gaps, or growing coupling with a known near-term change.
  • Low: naming, local clarity, optional simplification.

5. Principles behind the patterns

5.1 Three design principles

PrincipleViolation symptomRefactoring move
Encapsulate what variesA small requirement change forces edits across a large blockExtract the varying decision into a method, policy object, or interface
Program to an interface, not an implementationCallers name concrete classes and cannot substitute themIntroduce the narrowest interface the caller needs; inject implementations
Favor composition over inheritanceDeep hierarchies and combination subclassesHold collaborators as fields; delegate instead of inheriting behavior

5.2 SOLID in practice

PrincipleSmellMove
Single ResponsibilityA class changes for unrelated reasons (persistence, formatting, policy)Split by axis of change; extract collaborators
Open/ClosedEvery new case edits an existing if/switchAdd a polymorphic variant; keep selection at the boundary
Liskov SubstitutionA subclass throws, narrows, or changes documented behaviorRemove the inheritance; prefer composition or a separate interface
Interface SegregationImplementers stub out methods they never useSplit fat interfaces by client need
Dependency InversionHigh-level policy depends on a database, SDK, or frameworkDefine a port owned by policy; adapt infrastructure to it

Patterns are consequences of these principles, not replacements for them. When a pattern recommendation conflicts with a principle, the principle wins.


6. Relationship map

PatternOften combined withEasily confused with
Factory MethodTemplate Method, Abstract FactorySimple factory function, static helper
Abstract FactoryFactory Method, FacadeBuilder
BuilderComposite, Bridge (director/abstraction)Fluent setters
PrototypeCommand history, Composite, Memento alternativeCopy constructor without an interface
SingletonFacade, Abstract Factory, BuilderContainer-scoped instance
AdapterRepository/port boundariesBridge, Facade, Decorator
BridgeAbstract Factory, BuilderStrategy, State, Adapter
CompositeBuilder, Visitor, Iterator, Flyweight, Chain of ResponsibilityDecorator
DecoratorComposite, Builder (stack construction)Proxy, Adapter, Chain of Responsibility
FacadeAbstract Factory, SingletonMediator, Adapter
FlyweightCompositeSingleton, caching Proxy
ProxyFactory Method (creation), DecoratorDecorator, Adapter, Facade
Chain of ResponsibilityComposite, CommandDecorator, Observer
CommandMemento, Composite (macros), PrototypeStrategy, closures
IteratorComposite, Visitor, Factory MethodLanguage iterators
MediatorObserverFacade
MementoCommand, IteratorPrototype
ObserverMediator, CommandChain of Responsibility, pub/sub broker
StateState-machine library, BridgeStrategy
StrategyFactory Method, BridgeState, Command, Template Method
Template MethodFactory Method, hooksStrategy
VisitorComposite, IteratorStrategy, pattern matching

7. Output templates

7.1 Pattern recommendation

## Recommendation: <structure, not slogan>

**Context.** <language, lifecycle, change axis, variants today/soon>

**Forces.** <the concrete symptom and its evidence>

**Options.**
| Option | Fit | Cost | Why not |
| --- | --- | --- | --- |
| ... | ... | ... | ... |

**Recommendation.** <what to introduce, where, and the smallest first step>

**Why now.** <the change this absorbs; what happens if deferred>

**Cost and risks.** <indirection, migration, performance, team familiarity>

**Revisit trigger.** <measurement or change that would justify more/less>

7.2 Implementation plan

1. Behavior baseline: <tests / fixtures / recorded outputs>
2. Seam: <interface, constructor parameter, module boundary>
3. Extraction: <the one responsibility moved first>
4. Wiring: <composition root and selection rule>
5. Migration: <call sites in order; adapter or flag if needed>
6. Cleanup: <old path, dead branches, flags removed>
7. Verification: <variant tests, interaction tests, performance check>
8. Decision record: <force, choice, alternatives, revisit trigger>

7.3 Refactoring review summary

## Design review: <scope>

**Verdict.** <sound / needs structure / over-structured>

**High-signal findings.**
- <severity> <location>: <symptom> → <move>

**Do not change.**
- <areas that look unusual but are justified; why>

**Open questions.**
- <missing context that could change the recommendation>

8. Scope and source

This catalog follows the 22 Gang-of-Four patterns as presented in Dive Into Design Patterns by Alexander Shvets (2022), including the book's applicability criteria, trade-offs, and pattern relationships. Page ranges in each entry refer to that book and are provided for traceability; the guidance here is paraphrased and can be applied without the book.

Deliberately out of scope: architectural patterns (layered, hexagonal, CQRS, event sourcing, microservices), concurrency patterns, enterprise integration patterns, and framework-specific implementations. Mention them only when they are the real answer, and say so instead of forcing a GoF pattern onto the problem.

Habilidades Relacionadas