design-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDesign 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:
| Principle | Meaning | Violation Symptom |
|---|---|---|
| Encapsulate What Varies | Isolate changing parts from stable parts | Changes ripple through codebase |
| Program to Interfaces | Depend on abstractions, not concretions | Can't swap implementations |
| Composition Over Inheritance | Build behavior by composing objects | Deep rigid class hierarchies |
| Loose Coupling | Minimize interdependency between objects | Can't change one thing without breaking another |
| Open-Closed | Open for extension, closed for modification | Must edit existing code for new features |
| Single Responsibility | One reason to change per class | Classes doing too many things |
| Dependency Inversion | High-level modules don't depend on low-level | Business 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 ───────────────→ DTOCREATING 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 ───────────────→ DTOBy Symptom
按问题症状
| Symptom | Consider |
|---|---|
| Giant switch/if-else on type | Strategy, State, or polymorphism |
| Duplicate code across classes | Template Method, Strategy |
| Need to notify many objects of changes | Observer |
| Complex object creation logic | Factory, Builder |
| Adding features bloats class | Decorator |
| Third-party API doesn't fit your code | Adapter |
| Too many dependencies between components | Mediator, Facade |
| Can't test without database/network | Repository, Dependency Injection |
| Need undo/redo | Command |
| Object behavior depends on state | State |
| Request needs processing by multiple handlers | Chain 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 领域模型
| Factor | Transaction Script | Domain Model |
|---|---|---|
| Logic complexity | Simple (< 500 lines) | Complex, many rules |
| Business rules | Few, straightforward | Many, interacting |
| Operations | CRUD-heavy | Rich behavior |
| Team/timeline | Small team, quick delivery | Long-term maintenance |
| Testing | Integration tests | Unit 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)
第一层级:核心模式(优先掌握)
| Pattern | One-Line | When to Use | Reference |
|---|---|---|---|
| Strategy | Encapsulate interchangeable algorithms | Multiple ways to do something, swap at runtime | strategy.md |
| Observer | Notify dependents of state changes | Event systems, reactive updates | observer.md |
| Factory | Encapsulate object creation | Complex/conditional instantiation | factory.md |
| Decorator | Add behavior dynamically | Extend without inheritance | decorator.md |
| Command | Encapsulate requests as objects | Undo/redo, queuing, logging | command.md |
| 模式 | 核心描述 | 使用场景 | 参考链接 |
|---|---|---|---|
| 策略模式(Strategy) | 封装可互换的算法 | 同一种功能有多种实现方式,需要运行时切换 | strategy.md |
| 观察者模式(Observer) | 通知依赖对象状态变更 | 事件系统、响应式更新 | observer.md |
| 工厂模式(Factory) | 封装对象创建逻辑 | 复杂/条件化的对象实例化 | factory.md |
| 装饰器模式(Decorator) | 动态添加行为 | 无需继承即可扩展功能 | decorator.md |
| 命令模式(Command) | 将请求封装为对象 | 撤销/重做、队列、日志 | command.md |
Tier 2: Structural Patterns
第二层级:结构型模式
| Pattern | One-Line | When to Use | Reference |
|---|---|---|---|
| Adapter | Convert interfaces | Integrate incompatible code | adapter.md |
| Facade | Simplify complex subsystems | Hide complexity behind simple API | facade.md |
| Composite | Uniform tree structures | Part-whole hierarchies | composite.md |
| Proxy | Control access to objects | Lazy load, access control, caching | proxy.md |
| 模式 | 核心描述 | 使用场景 | 参考链接 |
|---|---|---|---|
| 适配器模式(Adapter) | 转换接口 | 集成不兼容的代码 | adapter.md |
| 外观模式(Facade) | 简化复杂子系统 | 用简单API隐藏底层复杂度 | facade.md |
| 组合模式(Composite) | 统一的树状结构 | 部分-整体层级关系 | composite.md |
| 代理模式(Proxy) | 控制对象访问 | 懒加载、访问控制、缓存 | proxy.md |
Tier 3: Enterprise/Architectural Patterns
第三层级:企业/架构模式
| Pattern | One-Line | When to Use | Reference |
|---|---|---|---|
| Repository | Collection-like data access | Decouple domain from data layer | repository.md |
| Unit of Work | Coordinate atomic changes | Transaction management | unit-of-work.md |
| Service Layer | Orchestrate business operations | Define application boundary | service-layer.md |
| DTO | Shape data for transfer | API contracts, prevent over-exposure | dto.md |
| 模式 | 核心描述 | 使用场景 | 参考链接 |
|---|---|---|---|
| 仓库模式(Repository) | 类集合形式的数据访问 | 解耦领域层和数据层 | repository.md |
| 工作单元(Unit of Work) | 协调原子性变更 | 事务管理 | unit-of-work.md |
| 服务层(Service Layer) | 编排业务操作 | 定义应用边界 | service-layer.md |
| 数据传输对象(DTO) | 格式化待传输的数据 | API契约、防止数据过度暴露 | dto.md |
Additional Important Patterns
其他重要模式
| Pattern | One-Line | When to Use | Reference |
|---|---|---|---|
| Builder | Step-by-step object construction | Complex objects, fluent APIs | builder.md |
| State | Behavior changes with state | State machines, workflow | state.md |
| Template Method | Algorithm skeleton with hooks | Framework extension points | template-method.md |
| Chain of Responsibility | Pass request along handlers | Middleware, pipelines | chain-of-responsibility.md |
| Mediator | Centralize complex communication | Reduce component coupling | mediator.md |
| Lazy Load | Defer expensive loading | Performance, large object graphs | lazy-load.md |
| Identity Map | Ensure object identity | ORM, prevent duplicates | identity-map.md |
| 模式 | 核心描述 | 使用场景 | 参考链接 |
|---|---|---|---|
| 建造者模式(Builder) | 分步构建对象 | 复杂对象创建、流式API | builder.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
常见错误
| Mistake | Symptom | Fix |
|---|---|---|
| Pattern Overuse | Simple operations require navigating many classes | Only use when solving real problem |
| Wrong Pattern | Code feels forced, awkward | Re-examine actual problem |
| Inheritance Abuse | Deep hierarchies, fragile base class | Favor composition (Strategy, Decorator) |
| Singleton Abuse | Global state, hidden dependencies, hard to test | Use dependency injection instead |
| Premature Abstraction | Interfaces with single implementation | Wait 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 Pattern | Based On | Description |
|---|---|---|
| Dependency Injection | Strategy + Factory | Container creates and injects dependencies |
| Middleware | Decorator + Chain of Responsibility | Request/response pipeline |
| Event Sourcing | Command | Store state changes as events |
| CQRS | Command/Query separation | Separate read/write models |
| Hooks (React/Vue) | Observer + Strategy | Functional 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
实现模式前请确认:
- 该模式能解决当前代码库中的真实问题
- 已经考虑过更简单的替代方案
- 该模式的权衡在当前场景下是可接受的
- 团队成员理解该模式
- 不会导致解决方案过度设计