Skip to main content
NOV 2026 Latest guide updates. Latest: AI Design Patterns Local vs cloud AI Grill me Changelog →
Claude Code Β· Build

AI design patterns

Last updated:

Your agent harness already speaks the patterns developers know: Observer, Mediator, Memento, Circuit Breaker, Saga. This page maps each one to the Claude Code mechanism behind it, then shows where the analogy breaks.

Work in progress. An attempt to connect two vocabularies, not a reference. The mappings are a reading to discuss and correct; if one does not hold for you, open an issue with the case where it breaks. The research also relies on two of the author's local research tools, which help find and cite source material: youtube-video-insights for timestamped talk transcripts and paper-insights for papers with verified citations.

Same shapes

Hooks react to events like observers, subagents isolate context like bulkheads, turn and budget limits stop a run like the static half of a circuit breaker. The vocabulary transfers, with limits this page names.

Weaker guarantees

The component in the middle is a model that decides at runtime. Order, restore and enforcement are no longer given; each card names what replaces them.

A check per pattern

Every row ends with a check you can run on your own harness.

Lineage

Three generations, one question

Object patterns (1994), integration and resilience patterns (2003 onward) and agent patterns (2024 onward) solve the same kind of problem. What changes is when the decision is taken.

Three generations of design patterns, framed by who chooses the structure: objects in 1994 (Observer, Strategy, Command; a developer writes how objects collaborate), services in 2003 (Router, Scatter-Gather, Pipes and Filters; services exchange messages and survive partial failure), and agents in 2024 (Orchestrator-workers, Evaluator-optimizer, Context isolation; a harness steers a model that picks its next step).
Framing after Jia Huang's Pattern Evolution: the shift from a structure chosen at design time to a decision taken at runtime by a model. Enlarge β†—
Crosswalk

Classic pattern, agent analogue, Claude Code mechanism

19 of 21 rows carry Our mapping: the sources give the generic agent analogue, and this guide maps it to Claude Code. Mechanisms link to the official documentation.

Map of the Claude Code harness: the agent loop in the center, connected to eight parts with their closest classic pattern. Hooks: Observer. Permission rules: Chain of Responsibility. Checkpoints: Memento. Subagents: Mediator and Bulkhead. MCP servers: Adapter. Skills: Template Method. CLAUDE.md: Facade. Turn and budget limits: Circuit Breaker.
Each pattern is the closest classic analogue for that part, not an equivalence. Enlarge β†—
Classic pattern Agent analogue In Claude Code Failure mode Evidence
Factory Method GoF creational
  • Subagent spawning from a named definition
The factory hands every product the full toolbox: a subagent definition without a tools field inherits every tool available to subagents. Consensus Our mapping
Singleton GoF creational
  • Shared tool registry
  • Layered memory governance: decide which state is shared, isolated, persisted, or ephemeral
Claude Code provides no Singleton here: several CLAUDE.md and memory files load and combine, and nothing enforces one instance or one access point. What carries over is the risk of unmanaged shared state: parallel sessions or agents that write the same memory file at the same time can overwrite each other's entries. Divergent Our mapping
Adapter GoF structural
  • Tool adapter that exposes an external system to the model
The adapter mirrors every upstream endpoint, so tool definitions crowd the context and the model picks among near-duplicate tools. Consensus Our mapping
Composite GoF structural
  • An agent that delegates to agents that can delegate again
Recursion without a budget: each layer multiplies token use. Claude Code caps nesting with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, which can be adjusted but not removed. Consensus Our mapping
Decorator GoF structural
  • Guardrail wrapped around a model call
  • Context-injection middleware that enriches each request
A classic decorator stack has a fixed order. Matching hooks run in parallel, so a wrapper that assumes another wrapper already ran is a race. Divergent Our mapping
Facade GoF structural
  • Project instruction file as the single entry point for conventions
The facade is read as a contract. The docs state that Claude treats CLAUDE.md as context, not enforced configuration: a rule written there is a request, not a guarantee. Single source Named by a source
Chain of Responsibility GoF behavioral
  • Hook or permission pipeline in front of tool calls
  • Agents chained so each one handles what it can and passes the rest
Teams expect declaration order or rule specificity to decide. The docs state that rules are evaluated deny, then ask, then allow, and specificity does not change that order: a broad deny beats a narrow allow. Divergent Our mapping
Command GoF behavioral
  • A tool call: a named action with structured arguments
The command object is written by the model. Without validation before dispatch, a malformed or out-of-scope argument executes as written. Consensus Our mapping
Mediator GoF behavioral
  • Orchestrator that coordinates workers which never talk to each other
The topology is not enforced, and the mediator can become the bottleneck. A subagent whose tools include SendMessage can message other named agents directly, without agent teams. And if workers return transcripts instead of summaries, the coordinating context fills with material it never reads again. Consensus Our mapping
Memento GoF behavioral
  • Checkpoint and rewind of agent state
The snapshot is partial. The docs state that checkpoints only track changes made through Claude's file editing tools; Bash commands and external processes are not captured, and edits made by a background subagent usually are not either. Consensus Our mapping
Observer GoF behavioral
  • Lifecycle hooks that react to agent events
Subscribers assume an order. The docs state that matching hooks run in parallel, that Claude Code combines their outputs after all of them finish, and that for permission decisions the most restrictive result applies: one hook's deny does not stop a sibling hook's side effects. Consensus Named by a source
Strategy GoF behavioral
  • Model or approach selected per task
  • Runtime strategy switching, with the harness recording why, at what cost, and how to roll back
The strategy changes silently. Nobody can tell afterwards which model produced which result or what the switch cost. Consensus Our mapping
Template Method GoF behavioral
  • System prompt that defines the steps
  • Fixed agent-loop skeleton with pluggable steps
A prose skeleton is not enforced: the model can skip or reorder a step, unlike a base class that calls the steps itself. Divergent Our mapping
Pipes and Filters Enterprise integration
  • Pipeline where each agent or model call is a filter
A filter emits free text that the next filter misreads, and the error travels down the pipe. Consensus Our mapping
Content-Based Router Enterprise integration
  • Classifier that sends a request to a specialized handler
Overlapping descriptions route the same request to different handlers from one run to the next. Consensus Our mapping
Scatter-Gather Enterprise integration
  • Parallel agents followed by a synthesis step
The gather step averages contradicting answers instead of reconciling them, and token cost grows with every branch. Consensus Our mapping
Bulkhead Distributed and resilience
  • Per-agent isolation of context, tools, and budget
Only the context is isolated. Parallel agents still share one checkout and overwrite each other's files. Consensus Our mapping
Circuit Breaker Distributed and resilience
  • Stop limits on turns, estimated cost, and loop depth
  • Breakers on tools, models, and the agent's own loop
These limits are bounded execution, not a breaker. A circuit breaker watches failures and opens; these caps are fixed before the run and do not track failures. --max-turns has no limit by default and counts turns, not cost. --max-budget-usd stops on a client-side cost estimate, and the docs warn that spend can pass the cap, so leave headroom. Consensus Our mapping
Saga Distributed and resilience
  • Compensating actions for an agent plan
Rewind is mistaken for compensation. It restores local file edits only; a push, an API call, or a database write stays done. Consensus Our mapping
Sidecar Distributed and resilience
  • The agent harness around the model loop
Policy lives in the prompt instead of the sidecar, so the model can talk itself out of it. A policy hook can also fail open: on most events, a hook that crashes or times out lets the action through unless it sets onFailure: "block". Single source Our mapping
Event Sourcing Distributed and resilience
  • The trace log as the event stream of an agent run
The transcript is taken for the whole event log. It records the conversation, including model outputs and tool results, so --resume rebuilds the conversation without calling the model again. It does not record the state of files, branches, or services the session changed, so it cannot rebuild that state, and the turns after a resume are new model calls. Single source Our mapping

Each row opens its full card in the guide: classic intent, every source, and the check to run. Last verified Oct 27, 2026 against the official Claude Code documentation.

Divergent

Where the sources disagree

The same classic pattern gets different agent analogues depending on the source. The disagreement is shown, not resolved.

Singleton

  • Shared tool registry Esther Aznar, Ivan Garcia Villar
  • Layered memory governance: decide which state is shared, isolated, persisted, or ephemeral Jia Huang

In Claude Code: CLAUDE.md hierarchy and auto memory (shared state, not a Singleton)

Decorator

  • Guardrail wrapped around a model call Esther Aznar, Ivan Garcia Villar
  • Context-injection middleware that enriches each request AgentPatterns.ai

In Claude Code: UserPromptSubmit and PostToolUse hooks

Chain of Responsibility

  • Hook or permission pipeline in front of tool calls AgentPatterns.ai, Ashish Patel
  • Agents chained so each one handles what it can and passes the rest Esther Aznar, Ivan Garcia Villar

In Claude Code: Permission rules: deny, then ask, then allow

Template Method

  • System prompt that defines the steps Esther Aznar, Ivan Garcia Villar
  • Fixed agent-loop skeleton with pluggable steps Ashish Patel

In Claude Code: Skills that define a procedure; Stop hook as the final step check

Limits

Where the analogy breaks

A classic pattern assumes the component in the middle executes what it is given. A model does not, and four guarantees change with it.

Four classic guarantees compared with Claude Code behavior: Decorator wrappers run in a fixed order, while matching hooks run in parallel; Memento restores the full state, while checkpoints track Claude's file edits only; Event Sourcing replay rebuilds the whole state, while a transcript keeps the conversation, not the state; a Facade enforces a contract, while CLAUDE.md is read as context, not enforced.
Each break is quoted from the official documentation below. Enlarge β†—
Decorator Wrappers run in a fixed order.
Hooks Matching hooks for one event run in parallel; for permission decisions the most restrictive result applies. Docs β†—
Memento The snapshot restores the full state.
Checkpoints Checkpoints track changes made through Claude's file editing tools only. Bash commands, external processes and most background subagent edits are not captured. Docs β†—
Event Sourcing Every state change is an event, so the log rebuilds the state.
Transcript The transcript restores the conversation, tool results included. It does not record the files, branches, or services the session changed, so it cannot rebuild them. Docs β†—
Facade The facade is code, so every call goes through it.
CLAUDE.md Claude treats CLAUDE.md as context, not enforced configuration. Blocking needs a deny rule, or a PreToolUse hook set to block when it fails: by default, a crashed hook lets the action through. Docs β†—
Native

Agent-native patterns

Close to classic patterns, but built around two things classic patterns never managed: a context window as the scarce resource and a model as the decision-maker.

Orchestrator-workers

A central model breaks a task down at runtime, delegates the parts, and synthesizes the results.

What is new: Closest classic pattern: Mediator. The difference is that the model decides the decomposition during the run instead of the designer drawing it. Delegation pays on parallel work: in Google Research's controlled study, every multi-agent variant degraded a sequential planning task by 39 to 70%.

Plan-then-execute

Separate a read-only planning phase from the phase that changes files.

What is new: The plan is a reviewable artifact written before any file changes, so a wrong approach can be caught before it costs edits. Reviewing it adds a checkpoint; it does not replace review of the code that follows, and the executing model can differ from the planning one (opusplan plans with Opus and executes with Sonnet).

Context compaction

Summarize the conversation when it approaches the window limit, and continue from the summary.

What is new: State is lossy by design: what the summary drops leaves the active context until something reloads it. Claude Code re-injects the project CLAUDE.md, auto memory, the plan, and invoked skills (capped), and re-reads up to five recent files; the rest of the conversation survives only as the summary.

Deterministic gate

Put anything that must always happen in code that runs outside the model's judgment.

What is new: Closest classic patterns: Sidecar and Chain of Responsibility. The difference is that the rest of the system is probabilistic, so the line between suggestion and enforcement has to be drawn on purpose.

Goal loop

Keep the agent working until a stated completion condition is met.

What is new: Whether the goal is met is judged by a model, so the condition must be checkable.

Anti-patterns

Where agent harnesses fail

Three families come from the MAST taxonomy of multi-agent failures (Cemri et al.). The fourth covers Claude Code mechanics MAST does not address. The category assignment is this guide's reading.

Ten harness anti-patterns in four families. Specification: prompt as enforcement, unbounded loop, step repetition. Inter-agent: context flooding, unguarded shared checkout. Verification: unverified done. Harness mechanics: rewind as rollback, ordered hooks assumption, specific allow overrides deny, untrusted content as instructions.
The table below gives the symptom and the fix for each one. Enlarge β†—
Anti-pattern Symptom Fix Family
Prompt as enforcement A must-never rule lives only in CLAUDE.md or a system prompt. Deterministic gate: a PreToolUse hook with onFailure: "block", or a deny rule, with a test. Deterministic gate, Facade Specification issues
Context flooding Workers return full transcripts or logs to the coordinating thread. Context isolation: ask each worker for a bounded final report. Context isolation, Mediator Inter-agent misalignment
Unbounded loop An automated run has no turn, cost, or depth limit. Bounded execution on every layer: --max-turns, --max-budget-usd with headroom, maxTurns, spawn depth. Circuit Breaker, Composite Specification issues
Unverified done The agent declares success without running a check, or stops early. Evaluator-optimizer with a real test, enforced by a Stop hook. Evaluator-optimizer, Template Method Task verification
Step repetition The agent redoes completed steps after an interruption or a reset of the conversation. Durable progress outside the context (a task list or a file) and idempotent side effects. Event Sourcing, Saga Specification issues
Rewind as rollback A team counts on /rewind to undo shell commands or remote effects. Saga thinking: git commits before risky work, a written compensation for each external effect. Memento, Saga Harness mechanics (beyond MAST)
Ordered hooks assumption A hook relies on another hook for the same event having run first. Independent observers: each hook passes or blocks on its own. Observer, Decorator Harness mechanics (beyond MAST)
Specific allow overrides deny A narrow allow rule is added to punch a hole in a broad deny. Permission rules are evaluated deny, then ask, then allow: narrow the deny instead. Chain of Responsibility Harness mechanics (beyond MAST)
Unguarded shared checkout Parallel write-capable agents edit the same working tree. Bulkhead: isolation: worktree per writing agent. Bulkhead, Scatter-Gather Inter-agent misalignment
Untrusted content as instructions Fetched pages, issue text, or tool output are allowed to steer the agent's next action. Trust boundary: treat external content as data, and keep write and network tools behind permission rules. Sidecar, Command Harness mechanics (beyond MAST)
Further reading

What practitioners have written

Articles and repositories that cover the same ground from other angles. None of them uses this page's crosswalk; each points to the closest pattern here.

Method

How a row gets in

A public source

At least one published crosswalk, catalog or paper maps the classic pattern to an agent analogue. Rows marked Consensus have two or more.

A documented mechanism

The Claude Code side links to the official documentation, checked on Oct 27, 2026. Repositories built from leaked source code are excluded.

A stated failure

A row without a failure mode and a check stays out. The dataset ships as JSON and through the guide's MCP server.

Full cards in the guide

Each pattern card lists the classic intent, every source with its reading, the Claude Code mechanism, the failure mode and the check to run.