¿Qué hace Design Patterns?
A working guide to the 22 Gang-of-Four patterns as framed in Dive Into Design Patterns (Alexander Shvets, 2022). It covers three jobs:
- Selection — turn a symptom into a shortlist, then a single recommendation.
- Implementation / refactoring — apply a pattern without breaking behavior.
- 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 frontmatternameis 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
- A pattern is a name for a structure that emerged, not a target. Recommend the structure; use the pattern name only to explain it.
- 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.
- Prefer the smallest structure that works: inline code → function → parameterized function → interface + one implementation → interface + multiple implementations → full pattern.
- Never add a pattern in review without evidence. Cite the duplication, branch count, dependency edge, or measured cost that justifies it.
- Name roles after the domain, not the pattern.
ShippingPolicybeatsShippingStrategy;DocumentPublisherbeatsDocumentObserverSubjectunless the pattern itself is the shared vocabulary. - Delete the old path. A pattern applied as a second parallel path with no removal plan is technical debt with extra steps.
- 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
| Symptom | First candidates | Consider instead |
|---|---|---|
new scattered across business logic; type chosen by config | Factory Method | DI container, simple factory function |
| Several related products must match (same theme, driver, vendor) | Abstract Factory | Factory Method per product, parameterized factory |
| Constructor has many optional parameters or flag arguments | Builder | Named/optional parameters, record + validation |
| Copying an object requires knowing its concrete class or private fields | Prototype | Copy constructor, serialization round-trip |
| One shared resource needs exactly one instance and global access | Singleton | Container-scoped singleton, module-level instance, explicit injection |
| Third-party/legacy interface does not fit | Adapter | Change your interface, anti-corruption layer |
| Two independent dimensions multiply subclasses (shape × color, device × OS) | Bridge | Split into two parameters, composition |
| Part-whole tree must be treated uniformly | Composite | Plain recursive functions over a data model |
| Behavior combinations explode subclasses (notify by email + SMS + Slack) | Decorator | Flags, middleware chain, strategy list |
| Clients drown in a multi-class subsystem | Facade | Narrow module API, service layer |
| Millions of similar objects exhaust memory | Flyweight | Interning, struct-of-arrays, lazy data |
| Access, lazy loading, caching, or remote calls must be transparent | Proxy | Explicit caching layer, repository, client wrapper |
| A request may be handled by one of several handlers in unknown order | Chain of Responsibility | Middleware pipeline, ordered list of functions |
| Actions must be queued, retried, logged, undone, or parameterized | Command | Closures, job queue payloads, event sourcing |
| Traversal must be uniform and independent of representation | Iterator | Language iterators/generators |
| Many components talk to many components; reusable components impossible | Mediator | Event bus, application service, Observer |
| Undo/rollback must restore state without exposing internals | Memento | Event log, database transaction, copy-on-write snapshot |
| One change must notify a dynamic set of consumers | Observer | Message broker, reactive streams, signals |
Large switch on state; transitions scattered | State | State-machine library, transition table, sum types |
| Multiple algorithms for one task; selection at runtime/config | Strategy | Function parameter, table lookup, polymorphism |
| Same algorithm skeleton, a few steps vary | Template Method | Strategy/composition, higher-order functions, hooks |
| Many unrelated operations over a stable object structure | Visitor | Pattern matching, external functions, serializers |
| Aggregate operations over a tree | Composite + Visitor | Recursive 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
| Pair | Choose the first when | Choose the second when |
|---|---|---|
| Factory Method / Abstract Factory | One product type; subclasses or config pick the concrete class | Several related products must be created and stay compatible |
| Abstract Factory / Builder | Products are returned immediately as a family | One complex product is assembled in steps and returned at the end |
| Factory Method / Builder | The variation is which class is created | The variation is how a complex object is configured |
| Builder / Prototype | Construction must be validated step by step | A fully configured object already exists and should be copied |
| Adapter / Bridge | Retrofitting incompatible code after the fact | Designing two independent hierarchies up front |
| Adapter / Facade | One interface must be translated to another | Many subsystem calls must be collapsed into one simple API |
| Decorator / Proxy | Add or remove responsibilities at runtime; client composes wrappers | Control access, lifetime, caching, or remoteness; proxy manages the service |
| Decorator / Chain of Responsibility | Every wrapper runs and adds behavior | A handler may stop the chain |
| Composite / Decorator | The goal is a tree with uniform leaf/container operations | The goal is extra responsibility on a node, not aggregation |
| Facade / Mediator | One-way simplification; subsystem does not know the facade | Two-way coordination; colleagues know and call the mediator |
| Mediator / Observer | Central coordination logic and star topology | One-to-many broadcast with no central policy |
| Strategy / State | Algorithms are independent; client switches | States trigger their own transitions and depend on each other |
| Strategy / Command | The question is how to perform one task | The question is what request to perform, store, or undo |
| Strategy / Template Method | Behavior varies per object at runtime via composition | Behavior varies per subclass at compile time via inheritance |
| Chain of Responsibility / Observer | Exactly one handler should act | All subscribers should be notified |
| Memento / Command | The requirement is state restoration | The requirement is request encapsulation, queueing, or replay |
| Memento / Prototype | Encapsulation must be preserved and history is needed | A simple copy of a simple object is enough |
| Iterator / Visitor | The requirement is traversal order and access | The requirement is an operation across many element types |
| Visitor / Strategy | Many operations over a stable element hierarchy | One interchangeable algorithm over a context |
| Flyweight / Singleton | Many immutable shared instances keyed by state | Exactly one mutable instance for the whole process |
| Composite / Flyweight | The hierarchy and uniform operations matter | Shared 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
| Pattern | Intent in one line | Reach for it when | Main cost |
|---|---|---|---|
| Factory Method | Subclasses decide which product class to instantiate | Creation type varies by config/subclass | New subclass per product |
| Abstract Factory | Create compatible families without concrete classes | Multiple products must match by variant | Adding a product kind touches every factory |
| Builder | Assemble a complex object step by step | Many optional parts; validation at the end | Builder classes plus optional director |
| Prototype | Clone without coupling to concrete classes | Configured objects should be copied | Deep-copy and identity hazards |
| Singleton | One instance, global access | A truly single shared resource | Hidden dependency; test and concurrency pain |
| Adapter | Translate one interface into another | Third-party or legacy incompatibility | Extra layer; leaky translations |
| Bridge | Separate abstraction from implementation | Two independent dimensions vary | Invented second dimension becomes overhead |
| Composite | Treat leaves and containers uniformly | Part-whole trees | Over-general component interface |
| Decorator | Wrap to add responsibilities at runtime | Combinable behaviors | Wrapper stacks and ordering |
| Facade | One simple API over a subsystem | Clients drown in subsystem details | God-object risk |
| Flyweight | Share immutable state across many objects | Memory-bound near-duplicates | CPU and complexity; immutability required |
| Proxy | Surrogate controlling access | Lazy load, secure, cache, remote | Latency and lifecycle complexity |
| Chain of Responsibility | Pass a request until handled | Unknown handler order/set | Requests can fall through |
| Command | Encapsulate a request as an object | Queue, retry, undo, replay | Class per action; history memory |
| Iterator | Traverse without exposing structure | Uniform or multiple traversals | Invalidation and snapshot semantics |
| Mediator | Centralize colleague communication | Many-to-many interactions | Mediator becomes a god object |
| Memento | Snapshot and restore state | Undo, rollback, checkpoints | Memory; retention policy |
| Observer | Notify subscribers of changes | Dynamic one-to-many events | Ordering, leaks, reentrancy |
| State | Behavior follows internal state | Lifecycle with many transitions | State class sprawl; transition ownership |
| Strategy | Swap algorithms via composition | Runtime algorithm choice | Client must understand variants |
| Template Method | Base class fixes the skeleton | Same flow, varying steps | Fragile inheritance; LSP risk |
| Visitor | Operations separate from structure | Many operations, stable elements | Adding 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.
- Unify all products behind one interface.
- Declare a factory method on the creator returning that interface.
- Replace direct
newcalls in creator logic with the factory call. - 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.
- Map product kinds × variants.
- Declare an interface per product kind.
- Declare one creation method per product kind on the abstract factory.
- Implement one factory per variant.
- 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.
- Identify the steps shared by all representations.
- Declare them on the builder interface.
- Implement a concrete builder per representation; expose the result at the end.
- Add a director only if several clients repeat the same step sequence.
- 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.
- Declare a clone method on the prototype interface.
- Implement a copy constructor that takes the source object.
- Clone by constructing a new instance from
this. - Copy owned mutable fields deeply; share only immutable data.
- 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.
- Make the constructor private (or otherwise prevent external construction).
- Store the instance in a private static field.
- Expose a static accessor with lazy or eager initialization.
- Make initialization thread-safe if the runtime is concurrent.
- 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.
- Define the interface the client needs (the target).
- Implement an adapter that holds or inherits the service.
- Translate parameters, return values, errors, and naming in the adapter.
- 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.
- Identify the two axes that vary independently.
- Put one axis in the abstraction hierarchy and the other behind an interface.
- Hold the implementation by composition, not inheritance.
- 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.
- Define the component interface shared by leaves and containers.
- Implement leaves with the primitive behavior.
- Implement containers holding child components and delegating/aggregating.
- Decide where
add/removelive (see pitfalls). - 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.
- Define the component interface shared by the target and wrappers.
- Implement the base decorator with a component field and pure delegation.
- Add concrete decorators that run logic before/after delegation.
- Let the client stack decorators in the required order.
- 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.
- Identify the few operations clients actually need.
- Implement them in a facade that orchestrates the subsystem.
- Move clients to the facade; keep the subsystem usable directly.
- 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.
- Split fields into intrinsic (shared, immutable) and extrinsic (per-instance).
- Make the flyweight immutable; initialize via constructor only.
- Pass extrinsic state into operations instead of storing it in the flyweight.
- Add a factory keyed by intrinsic state; return existing instances.
- 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.
- Extract or confirm the service interface.
- Implement the proxy against the same interface.
- Hold or create the real service inside the proxy.
- Intercept calls for the specific concern, then delegate.
- 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.
- Declare a handler interface with the handling operation.
- Optionally add a base handler holding the next link.
- Implement handlers that decide to handle, stop, or forward.
- Assemble the chain in one place; define a terminal handler or fallback.
- 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.
- Declare a command interface with a minimal execution method.
- Implement one command per request, storing receiver and arguments.
- Make the invoker hold and trigger commands without knowing their details.
- Add
undoonly if the command can reverse its effects correctly. - 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.
- Declare
next/hasNext(or the language equivalent). - Declare a factory method on the collection returning an iterator.
- Implement a concrete iterator holding the collection reference and cursor.
- Decide between live iteration and snapshot iteration.
- 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.
- Identify the tightly coupled group and the interactions to centralize.
- Declare a mediator notification interface.
- Implement the mediator with references to the colleagues.
- Replace direct colleague-to-colleague calls with mediator notifications.
- 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.
- Decide what constitutes the originator's state.
- Create an immutable memento type holding that state.
- Add
save()andrestore(memento)to the originator. - Restrict memento access to the originator (nested class, friend, module privacy, or an opaque token).
- 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.
- Split the independent state owner from the dependent reactions.
- Declare a subscriber interface with the notification payload.
- Add subscribe/unsubscribe to the publisher.
- Notify all subscribers on the relevant state change.
- 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.
- Declare the operations that vary by state.
- Implement one state class per state.
- Give the context a state reference and delegate to it.
- Decide whether the context or the state owns transitions.
- 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.
- Identify the algorithm that varies and its inputs/outputs.
- Declare a strategy interface for that algorithm.
- Extract each variant into a concrete strategy.
- Give the context a strategy reference and a way to replace it.
- 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.
- Decompose the algorithm into steps.
- Implement the template method and make it non-overridable.
- Declare varying steps as abstract; give stable steps default behavior.
- Add empty hooks only where subclasses legitimately need optional extension.
- 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.
- Declare a visit method per concrete element type.
- Add
accept(visitor)to the element interface. - Implement
acceptasvisitor.visit(this)in each element. - Implement one concrete visitor per operation.
- 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
- 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.
- 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".
- Introduce the smallest seam. Usually an interface at the boundary, a constructor parameter, or a function parameter. Do not add the whole pattern yet.
- Move one responsibility at a time. Extract the varying code; leave stable code in place. Keep commits small and behavior-preserving.
- Wire at the composition root. Choose concrete implementations at startup, configuration, or request boundary — never deep inside domain logic.
- Delete the replaced path. Remove dead branches, old constructors, and feature flags once parity is proven.
- Add variant tests. One test per implementation, plus interaction tests for ordering, delegation, notification, and undo.
- Record the decision. A short note: force, chosen structure, alternatives, cost, and the condition that would justify revisiting.
3.2 Refactoring moves
| Current smell | First move | Pattern candidate | Caution |
|---|---|---|---|
new ConcreteX() in domain logic | Extract creation to one function | Factory Method | Do not create a class per type if a registry suffices |
Same switch selecting product family | Group constructors behind one interface | Abstract Factory | New product kinds will break the interface |
| Constructor with 10 optional parameters | Introduce a parameter object | Builder | Validate at build time; avoid mutable half-built objects |
| Copying fields from outside the class | Add a copy constructor | Prototype | Handle deep copies and identity explicitly |
Global getInstance() calls everywhere | Inject the dependency | Singleton (remove it) | Prefer container scope; keep a module-level instance only if needed |
| Vendor type leaking through the app | Define a port; wrap the vendor | Adapter | Keep translation free of business rules |
if (shape == CIRCLE && color == RED) combinations | Split the two dimensions | Bridge | Only if both dimensions truly vary |
instanceof/type checks over a tree | Add a common component interface | Composite | Decide transparency vs safety for child operations |
| Subclass per feature combination | Wrap the base object | Decorator | Watch order, identity, and stack construction |
| Client orchestrates five subsystem classes | Add one entry-point function | Facade | Do not hide operations clients still need |
| Millions of duplicate value objects | Extract immutable shared state | Flyweight | Measure memory first; bound the cache |
| Expensive object constructed eagerly | Add a lazy wrapper | Proxy | Handle concurrent init and failure |
| Nested validation/authorization blocks | Extract handlers into a list | Chain of Responsibility | Define the unhandled terminal case |
| UI callbacks call business methods directly | Turn each action into an object | Command | Use closures if undo/queueing is not required |
| Custom traversal duplicated in clients | Move cursor state into an iterator | Iterator | Use language iterators when available |
| UI controls reference each other | Route events through a coordinator | Mediator | Split before it becomes a god object |
| Undo implemented by public state fields | Add an opaque snapshot type | Memento | Bound history; version persisted snapshots |
| Model calls every dependent directly | Add subscribe/notify | Observer | Define unsubscribe and error isolation |
Large switch on status in many methods | Move behavior into state classes | State | Decide who owns transitions |
Runtime if chooses among algorithms | Extract algorithm interface | Strategy | Do not wrap one stable algorithm |
| Copy-pasted algorithm with small differences | Pull the skeleton into a base class | Template Method | Watch LSP and step count |
| Export/report methods on every model class | Move operations into a visitor | Visitor | Adding element types becomes expensive |
3.3 Language shortcuts
Use the idiom before the ceremony. The pattern's intent matters, not its class diagram.
| Language capability | Replaces or simplifies |
|---|---|
| First-class functions, closures | Strategy, Command (without undo), Chain of Responsibility, Observer callbacks |
| Built-in iterators/generators | Iterator |
| Events, signals, reactive streams | Observer |
| Sum types, sealed hierarchies, pattern matching | State, Visitor, Command classification |
| Dependency injection / containers | Singleton lifecycle, factory wiring, Abstract Factory selection |
Immutable records, copy constructors, with-style updates | Prototype, Builder for data objects |
| Modules/packages with explicit exports | Facade |
| Middleware pipelines | Chain of Responsibility, Decorator |
| Interning/pools in the runtime | Flyweight |
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
| Signal | Evidence to look for | Likely direction |
|---|---|---|
| Shotgun surgery | One change edits many unrelated files | Missing boundary; Facade/Mediator or a module split |
| Repeated type dispatch | instanceof, switch on type in several places | Composite/Visitor or polymorphism |
| Constructor pain | Many optional args, booleans, nulls | Builder or parameter object |
| Creation coupling | Domain code names concrete infrastructure | Factory Method/Abstract Factory + DI |
| Subclass explosion | Class names encode combinations | Bridge, Decorator, or Strategy |
| Global access | Static singletons reached from everywhere | Injection, scoped lifetime |
| Tangled UI/model | Controls call each other and the model | Mediator + Observer |
| Duplicated traversal | Cursor logic copied into clients | Iterator |
| Manual undo | Ad-hoc state copies and restore code | Command + Memento |
| Repeated vendor glue | Same translation in many call sites | Adapter at one boundary |
| Memory growth | Many near-identical objects | Flyweight after profiling |
| Latency from eager work | Expensive setup on every path | Proxy/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
| Principle | Violation symptom | Refactoring move |
|---|---|---|
| Encapsulate what varies | A small requirement change forces edits across a large block | Extract the varying decision into a method, policy object, or interface |
| Program to an interface, not an implementation | Callers name concrete classes and cannot substitute them | Introduce the narrowest interface the caller needs; inject implementations |
| Favor composition over inheritance | Deep hierarchies and combination subclasses | Hold collaborators as fields; delegate instead of inheriting behavior |
5.2 SOLID in practice
| Principle | Smell | Move |
|---|---|---|
| Single Responsibility | A class changes for unrelated reasons (persistence, formatting, policy) | Split by axis of change; extract collaborators |
| Open/Closed | Every new case edits an existing if/switch | Add a polymorphic variant; keep selection at the boundary |
| Liskov Substitution | A subclass throws, narrows, or changes documented behavior | Remove the inheritance; prefer composition or a separate interface |
| Interface Segregation | Implementers stub out methods they never use | Split fat interfaces by client need |
| Dependency Inversion | High-level policy depends on a database, SDK, or framework | Define 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
| Pattern | Often combined with | Easily confused with |
|---|---|---|
| Factory Method | Template Method, Abstract Factory | Simple factory function, static helper |
| Abstract Factory | Factory Method, Facade | Builder |
| Builder | Composite, Bridge (director/abstraction) | Fluent setters |
| Prototype | Command history, Composite, Memento alternative | Copy constructor without an interface |
| Singleton | Facade, Abstract Factory, Builder | Container-scoped instance |
| Adapter | Repository/port boundaries | Bridge, Facade, Decorator |
| Bridge | Abstract Factory, Builder | Strategy, State, Adapter |
| Composite | Builder, Visitor, Iterator, Flyweight, Chain of Responsibility | Decorator |
| Decorator | Composite, Builder (stack construction) | Proxy, Adapter, Chain of Responsibility |
| Facade | Abstract Factory, Singleton | Mediator, Adapter |
| Flyweight | Composite | Singleton, caching Proxy |
| Proxy | Factory Method (creation), Decorator | Decorator, Adapter, Facade |
| Chain of Responsibility | Composite, Command | Decorator, Observer |
| Command | Memento, Composite (macros), Prototype | Strategy, closures |
| Iterator | Composite, Visitor, Factory Method | Language iterators |
| Mediator | Observer | Facade |
| Memento | Command, Iterator | Prototype |
| Observer | Mediator, Command | Chain of Responsibility, pub/sub broker |
| State | State-machine library, Bridge | Strategy |
| Strategy | Factory Method, Bridge | State, Command, Template Method |
| Template Method | Factory Method, hooks | Strategy |
| Visitor | Composite, Iterator | Strategy, 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.