design-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Design Patterns

设计模式

Overview

概述

Design patterns are proven solutions to recurring software design problems. They provide a shared vocabulary for discussing design and capture collective wisdom refined through decades of real-world use.
Core Philosophy: Patterns are templates you adapt to your context, not blueprints to copy. Use the right pattern when it genuinely simplifies your design—not to impress or over-engineer.
设计模式是针对反复出现的软件设计问题的已验证解决方案。它们提供了讨论设计的通用词汇,沉淀了数十年实际应用中打磨出的集体智慧。
核心思想: 模式是供你结合自身场景适配的模板,而非直接照搬的蓝图。只有当它确实能简化你的设计时再使用合适的模式,不要为了炫技或者过度设计而套用。

Foundational Principles

基础原则

These principles underpin all good design:
PrincipleMeaningViolation Symptom
Encapsulate What VariesIsolate changing parts from stable partsChanges ripple through codebase
Program to InterfacesDepend on abstractions, not concretionsCan't swap implementations
Composition Over InheritanceBuild behavior by composing objectsDeep rigid class hierarchies
Loose CouplingMinimize interdependency between objectsCan't change one thing without breaking another
Open-ClosedOpen for extension, closed for modificationMust edit existing code for new features
Single ResponsibilityOne reason to change per classClasses doing too many things
Dependency InversionHigh-level modules don't depend on low-levelBusiness logic coupled to infrastructure
以下原则是所有优秀设计的底层支撑:
原则含义违反症状
封装变化点将易变部分和稳定部分隔离修改会波及整个代码库
面向接口编程依赖抽象而非具体实现无法替换实现方案
组合优于继承通过组合对象构建行为深度僵化的类层级
松耦合最小化对象之间的相互依赖修改一个功能就会破坏其他功能
开闭原则对扩展开放,对修改关闭新增功能必须修改现有代码
单一职责原则每个类只有一个变更原因单个类承担了过多功能
依赖倒置原则高层模块不依赖低层模块业务逻辑和基础设施耦合

Pattern Selection Guide

模式选择指南

By Problem Type

按问题类型

CREATING OBJECTS
├── Complex/conditional creation ──────────→ Factory Method
├── Families of related objects ───────────→ Abstract Factory
├── Step-by-step construction ─────────────→ Builder
├── Clone existing objects ────────────────→ Prototype
└── Single instance needed ────────────────→ Singleton (use sparingly!)

STRUCTURING/COMPOSING OBJECTS
├── Incompatible interface ────────────────→ Adapter
├── Simplify complex subsystem ────────────→ Facade
├── Tree/hierarchy structure ──────────────→ Composite
├── Add behavior dynamically ──────────────→ Decorator
└── Control access to object ──────────────→ Proxy

MANAGING COMMUNICATION/BEHAVIOR
├── One-to-many notification ──────────────→ Observer
├── Encapsulate requests as objects ───────→ Command
├── Behavior varies by internal state ─────→ State
├── Swap algorithms at runtime ────────────→ Strategy
├── Algorithm skeleton with hooks ─────────→ Template Method
├── Reduce N-to-N communication ───────────→ Mediator
└── Sequential handlers ───────────────────→ Chain of Responsibility

MANAGING DATA ACCESS
├── Abstract data source ──────────────────→ Repository
├── Track changes for atomic commit ───────→ Unit of Work
├── Ensure object identity ────────────────→ Identity Map
├── Defer expensive loading ───────────────→ Lazy Load
├── Map objects to database ───────────────→ Data Mapper
└── Shape data for transfer ───────────────→ DTO
CREATING OBJECTS
├── Complex/conditional creation ──────────→ Factory Method
├── Families of related objects ───────────→ Abstract Factory
├── Step-by-step construction ─────────────→ Builder
├── Clone existing objects ────────────────→ Prototype
└── Single instance needed ────────────────→ Singleton (use sparingly!)

STRUCTURING/COMPOSING OBJECTS
├── Incompatible interface ────────────────→ Adapter
├── Simplify complex subsystem ────────────→ Facade
├── Tree/hierarchy structure ──────────────→ Composite
├── Add behavior dynamically ──────────────→ Decorator
└── Control access to object ──────────────→ Proxy

MANAGING COMMUNICATION/BEHAVIOR
├── One-to-many notification ──────────────→ Observer
├── Encapsulate requests as objects ───────→ Command
├── Behavior varies by internal state ─────→ State
├── Swap algorithms at runtime ────────────→ Strategy
├── Algorithm skeleton with hooks ─────────→ Template Method
├── Reduce N-to-N communication ───────────→ Mediator
└── Sequential handlers ───────────────────→ Chain of Responsibility

MANAGING DATA ACCESS
├── Abstract data source ──────────────────→ Repository
├── Track changes for atomic commit ───────→ Unit of Work
├── Ensure object identity ────────────────→ Identity Map
├── Defer expensive loading ───────────────→ Lazy Load
├── Map objects to database ───────────────→ Data Mapper
└── Shape data for transfer ───────────────→ DTO

By Symptom

按问题症状

SymptomConsider
Giant switch/if-else on typeStrategy, State, or polymorphism
Duplicate code across classesTemplate Method, Strategy
Need to notify many objects of changesObserver
Complex object creation logicFactory, Builder
Adding features bloats classDecorator
Third-party API doesn't fit your codeAdapter
Too many dependencies between componentsMediator, Facade
Can't test without database/networkRepository, Dependency Injection
Need undo/redoCommand
Object behavior depends on stateState
Request needs processing by multiple handlersChain of Responsibility
症状可考虑的方案
基于类型的巨型switch/if-else判断策略模式(Strategy)、状态模式(State)或多态
跨类重复代码模板方法模式(Template Method)、策略模式(Strategy)
需要通知多个对象状态变更观察者模式(Observer)
复杂的对象创建逻辑工厂模式(Factory)、建造者模式(Builder)
新增功能导致类过度膨胀装饰器模式(Decorator)
第三方API和你的代码不兼容适配器模式(Adapter)
组件之间依赖关系过多中介者模式(Mediator)、外观模式(Facade)
没有数据库/网络就无法测试仓库模式(Repository)、依赖注入
需要实现撤销/重做功能命令模式(Command)
对象行为随状态变化状态模式(State)
请求需要经过多个处理环节责任链模式(Chain of Responsibility)

Domain Logic: Transaction Script vs Domain Model

领域逻辑:事务脚本 vs 领域模型

FactorTransaction ScriptDomain Model
Logic complexitySimple (< 500 lines)Complex, many rules
Business rulesFew, straightforwardMany, interacting
OperationsCRUD-heavyRich behavior
Team/timelineSmall team, quick deliveryLong-term maintenance
TestingIntegration testsUnit tests on domain
Rule of thumb: Start with Transaction Script. Refactor to Domain Model when procedural code becomes hard to maintain.
考量因素事务脚本(Transaction Script)领域模型(Domain Model)
逻辑复杂度简单(<500行代码)复杂,包含大量规则
业务规则数量少,逻辑直接数量多,相互关联
操作类型以CRUD为主丰富的行为逻辑
团队/项目周期小团队,快速交付需要长期维护
测试方式集成测试针对领域逻辑的单元测试
经验法则: 初始阶段优先使用事务脚本,当过程式代码难以维护时再重构为领域模型。

Quick Reference

快速参考

Tier 1: Essential Patterns (Master First)

第一层级:核心模式(优先掌握)

PatternOne-LineWhen to UseReference
StrategyEncapsulate interchangeable algorithmsMultiple ways to do something, swap at runtimestrategy.md
ObserverNotify dependents of state changesEvent systems, reactive updatesobserver.md
FactoryEncapsulate object creationComplex/conditional instantiationfactory.md
DecoratorAdd behavior dynamicallyExtend without inheritancedecorator.md
CommandEncapsulate requests as objectsUndo/redo, queuing, loggingcommand.md
模式核心描述使用场景参考链接
策略模式(Strategy)封装可互换的算法同一种功能有多种实现方式,需要运行时切换strategy.md
观察者模式(Observer)通知依赖对象状态变更事件系统、响应式更新observer.md
工厂模式(Factory)封装对象创建逻辑复杂/条件化的对象实例化factory.md
装饰器模式(Decorator)动态添加行为无需继承即可扩展功能decorator.md
命令模式(Command)将请求封装为对象撤销/重做、队列、日志command.md

Tier 2: Structural Patterns

第二层级:结构型模式

PatternOne-LineWhen to UseReference
AdapterConvert interfacesIntegrate incompatible codeadapter.md
FacadeSimplify complex subsystemsHide complexity behind simple APIfacade.md
CompositeUniform tree structuresPart-whole hierarchiescomposite.md
ProxyControl access to objectsLazy load, access control, cachingproxy.md
模式核心描述使用场景参考链接
适配器模式(Adapter)转换接口集成不兼容的代码adapter.md
外观模式(Facade)简化复杂子系统用简单API隐藏底层复杂度facade.md
组合模式(Composite)统一的树状结构部分-整体层级关系composite.md
代理模式(Proxy)控制对象访问懒加载、访问控制、缓存proxy.md

Tier 3: Enterprise/Architectural Patterns

第三层级:企业/架构模式

PatternOne-LineWhen to UseReference
RepositoryCollection-like data accessDecouple domain from data layerrepository.md
Unit of WorkCoordinate atomic changesTransaction managementunit-of-work.md
Service LayerOrchestrate business operationsDefine application boundaryservice-layer.md
DTOShape data for transferAPI contracts, prevent over-exposuredto.md
模式核心描述使用场景参考链接
仓库模式(Repository)类集合形式的数据访问解耦领域层和数据层repository.md
工作单元(Unit of Work)协调原子性变更事务管理unit-of-work.md
服务层(Service Layer)编排业务操作定义应用边界service-layer.md
数据传输对象(DTO)格式化待传输的数据API契约、防止数据过度暴露dto.md

Additional Important Patterns

其他重要模式

PatternOne-LineWhen to UseReference
BuilderStep-by-step object constructionComplex objects, fluent APIsbuilder.md
StateBehavior changes with stateState machines, workflowstate.md
Template MethodAlgorithm skeleton with hooksFramework extension pointstemplate-method.md
Chain of ResponsibilityPass request along handlersMiddleware, pipelineschain-of-responsibility.md
MediatorCentralize complex communicationReduce component couplingmediator.md
Lazy LoadDefer expensive loadingPerformance, large object graphslazy-load.md
Identity MapEnsure object identityORM, prevent duplicatesidentity-map.md
模式核心描述使用场景参考链接
建造者模式(Builder)分步构建对象复杂对象创建、流式APIbuilder.md
状态模式(State)行为随状态变化状态机、工作流state.md
模板方法模式(Template Method)带扩展点的算法骨架框架扩展点template-method.md
责任链模式(Chain of Responsibility)沿处理链传递请求中间件、流水线chain-of-responsibility.md
中介者模式(Mediator)集中复杂通信逻辑降低组件耦合mediator.md
懒加载(Lazy Load)延迟高开销的加载操作性能优化、大型对象图lazy-load.md
标识映射(Identity Map)保证对象唯一性ORM、避免重复对象identity-map.md

Common Mistakes

常见错误

MistakeSymptomFix
Pattern OveruseSimple operations require navigating many classesOnly use when solving real problem
Wrong PatternCode feels forced, awkwardRe-examine actual problem
Inheritance AbuseDeep hierarchies, fragile base classFavor composition (Strategy, Decorator)
Singleton AbuseGlobal state, hidden dependencies, hard to testUse dependency injection instead
Premature AbstractionInterfaces with single implementationWait for real need to vary
错误症状修复方案
模式滥用简单操作需要跳转多个类才能理解只在解决真实问题时使用模式
模式错用代码逻辑生硬、别扭重新审视实际问题
继承滥用层级过深、基类脆弱优先使用组合(策略模式、装饰器模式)
单例模式滥用全局状态、隐式依赖、难以测试改用依赖注入
过早抽象接口只有一个实现等到确实需要扩展时再抽象

Anti-Patterns to Recognize

需要注意的反模式

  • God Object: One class does everything → Split using SRP
  • Anemic Domain Model: Objects are just data bags → Move behavior to objects
  • Golden Hammer: Same pattern everywhere → Match pattern to problem
  • Lava Flow: Dead code nobody removes → Delete it, VCS has your back
  • 上帝对象: 单个类承担所有功能 → 按照单一职责原则拆分
  • 贫血领域模型: 对象仅包含数据 → 将行为逻辑迁移到对象内
  • 黄金锤子: 所有场景都用同一种模式 → 针对问题匹配合适的模式
  • 熔岩流: 无人移除的死代码 → 直接删除,版本控制系统会保留历史记录

Modern Variations

现代变体

Modern PatternBased OnDescription
Dependency InjectionStrategy + FactoryContainer creates and injects dependencies
MiddlewareDecorator + Chain of ResponsibilityRequest/response pipeline
Event SourcingCommandStore state changes as events
CQRSCommand/Query separationSeparate read/write models
Hooks (React/Vue)Observer + StrategyFunctional lifecycle subscriptions
现代模式基于的基础模式描述
依赖注入策略模式 + 工厂模式容器负责创建并注入依赖
中间件装饰器模式 + 责任链模式请求/响应处理流水线
事件溯源命令模式将状态变更存储为事件序列
CQRS命令/查询分离分离读模型和写模型
Hooks (React/Vue)观察者模式 + 策略模式函数式生命周期订阅

Implementation Checklist

实现检查清单

Before implementing a pattern:
  • Pattern solves a real problem in this codebase
  • Considered simpler alternatives
  • Trade-offs acceptable for this context
  • Team understands the pattern
  • Won't over-engineer the solution
实现模式前请确认:
  • 该模式能解决当前代码库中的真实问题
  • 已经考虑过更简单的替代方案
  • 该模式的权衡在当前场景下是可接受的
  • 团队成员理解该模式
  • 不会导致解决方案过度设计