跳到主要内容

Design Patterns

"Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem." — Christopher Alexander

Design patterns are reusable solutions to commonly occurring problems in software design. The 23 patterns documented by the Gang of Four (GoF) in 1994 remain the foundational vocabulary of software architecture.

This guide goes beyond textbook explanations — each pattern is paired with its practical application in AI Agent development, showing how classic design wisdom maps directly to modern LLM-powered systems.


The 23 Patterns at a Glance

Patterns are organized into three categories based on their purpose:

Creational Patterns (5)

How objects are created — controlling instantiation to provide flexibility and reuse.

PatternIntentAgent Application
SingletonEnsure only one instance existsGlobal Agent config center, LLM client connection pool
Factory MethodDelegate instantiation to subclassesAgent type factory (ReAct / Plan-and-Execute / Reflexion)
Abstract FactoryCreate families of related objectsMulti-LLM Provider adaptation (OpenAI / Claude / Gemini)
BuilderStep-by-step complex object constructionComplex Prompt builder, Agent config chain assembly
PrototypeClone existing objectsAgent template cloning, conversation session snapshots

Structural Patterns (7)

How objects are composed — building relationships between classes and objects.

PatternIntentAgent Application
AdapterBridge incompatible interfacesUnified LLM API adapter, MCP Tool protocol conversion
BridgeDecouple abstraction from implementationAgent reasoning engine decoupled from tool sets
CompositeTree structures of objectsMulti-level Agent composition (Supervisor → Worker → Sub-agent)
DecoratorAdd responsibilities dynamicallyRuntime Agent capability injection (RAG, Memory, Guardrails)
FacadeSimplified interface to complex subsystemSimplified Agent API hiding orchestration complexity
FlyweightShare objects to support large quantitiesShared Tool schemas, Embedding cache, Prompt token dedup
ProxyPlaceholder controlling accessAgent access control, lazy loading, rate limiting

Behavioral Patterns (11)

How objects communicate — assigning responsibilities and algorithms.

PatternIntentAgent Application
Chain of ResponsibilityPass request along handler chainAgent middleware pipeline (Validation → Preprocessing → LLM → Post-processing)
CommandEncapsulate request as objectAgent Action objectification (Undo/Redo, Action log, Replay)
InterpreterDefine a grammar and interpreterAgent DSL parsing (natural language → structured instructions)
IteratorSequential access to collectionStreaming token iteration, document chunk traversal
MediatorCentralize communication between objectsMulti-Agent coordination center (Event Bus, Message Router)
MementoCapture and restore object stateAgent state snapshot & recovery (Checkpoint, version rollback)
ObserverNotify dependents of state changesAgent event-driven architecture (state change notifications, progress monitoring)
StateAlter behavior when state changesAgent state machine (Idle → Thinking → Acting → Observing)
StrategyEncapsulate interchangeable algorithmsReasoning strategy switching (ReAct vs CoT vs ToT)
Template MethodDefine algorithm skeleton in base classAgent execution framework (custom Pre/Post hooks)
VisitorSeparate operations from object structureAgent output post-processing pipeline (safety review, format conversion, quality scoring)

Why Learn Design Patterns for Agent Development?

Building AI Agent systems involves many of the same structural challenges that GoF patterns solve:

  1. Managing complexity — Agent orchestration with multiple LLM calls, tool invocations, and state transitions mirrors classic workflow patterns
  2. Extensibility — New tools, providers, and reasoning strategies should plug in without rewriting core logic
  3. Testability — Clean separation of concerns (Strategy, Bridge) makes it possible to unit-test Agent behavior
  4. Maintainability — Well-structured Agent code (Facade, Mediator) is easier to debug and evolve

Learning Path

For Beginners

  1. Start with Creational Patterns — understand how to control object creation
  2. Move to Structural Patterns — learn how to compose flexible architectures
  3. Finish with Behavioral Patterns — master object communication and responsibility

For Agent Developers

  1. Read the Agent Application section of each pattern
  2. Look for patterns you're already using implicitly — give them names
  3. Apply patterns deliberately when designing new Agent features
  4. Use the Mermaid diagrams to communicate your architecture to teammates

Relationship to Agent Architecture Patterns

This guide covers classic GoF design patterns (object-level, code-level solutions). For Agent-specific architectural patterns (system-level, multi-agent coordination), see:

The two complement each other: GoF patterns are the building blocks; Agent patterns are the blueprints.


Quick Reference

CategoryPatternsKey Insight
Creational5 patternsControl how and when objects are created
Structural7 patternsControl how objects are composed and connected
Behavioral11 patternsControl how objects communicate and divide work

Next Steps

Dive into each category:

  • Creational Patterns — Singleton, Factory Method, Abstract Factory, Builder, Prototype
  • Structural Patterns — Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy
  • Behavioral Patterns — Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor