design-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Design Patterns

设计模式

Proven architectural patterns for building maintainable, extensible, and testable TypeScript codebases. All 22 Gang of Four patterns with practical implementations.
经过验证的架构模式,用于构建可维护、可扩展且可测试的TypeScript代码库。包含全部22种Gang of Four模式的实用实现。

When to Apply

适用场景

Reference these patterns when:
  • Solving recurring architectural problems
  • Refactoring tightly coupled code
  • Building plugin/extension systems
  • Making code more testable via dependency injection
  • Reviewing PRs with architectural concerns
  • Choosing between inheritance and composition
在以下场景中参考这些模式:
  • 解决重复出现的架构问题
  • 重构耦合紧密的代码
  • 构建插件/扩展系统
  • 通过依赖注入提升代码可测试性
  • 评审涉及架构问题的PR
  • 在继承与组合之间做选择

Pattern Categories

模式分类

Creational Patterns

创建型模式

Create objects flexibly, hiding creation logic from consumers.
PatternIntent
Factory MethodDelegate object creation to subclasses
Abstract FactoryCreate families of related objects without concrete types
BuilderConstruct complex objects step-by-step
PrototypeClone existing objects instead of building from scratch
SingletonEnsure exactly one instance with global access
See
references/CREATIONAL.md
for implementations.
灵活创建对象,向使用者隐藏创建逻辑。
模式意图
Factory Method将对象创建委托给子类
Abstract Factory创建相关对象族,无需指定具体类型
Builder分步构建复杂对象
Prototype克隆现有对象而非从零构建
Singleton确保全局仅存在一个实例并提供全局访问
详见
references/CREATIONAL.md
中的实现。

Structural Patterns

结构型模式

Compose classes and objects into larger, flexible structures.
PatternIntent
AdapterMake incompatible interfaces work together
BridgeSeparate abstraction from implementation
CompositeTreat individual objects and compositions uniformly
DecoratorAttach responsibilities dynamically without subclassing
FacadeSimplify complex subsystem with a unified interface
FlyweightShare common state to reduce memory across many objects
ProxyControl access to an object through a substitute
See
references/STRUCTURAL.md
for implementations.
将类和对象组合成更大、更灵活的结构。
模式意图
Adapter使不兼容的接口能够协同工作
Bridge将抽象与实现分离
Composite统一对待单个对象和对象组合
Decorator在不使用子类化的情况下动态添加职责
Facade用统一接口简化复杂子系统
Flyweight共享公共状态以减少大量对象的内存占用
Proxy通过代理对象控制对目标对象的访问
详见
references/STRUCTURAL.md
中的实现。

Behavioral Patterns

行为型模式

Manage algorithms, responsibilities, and communication between objects.
PatternIntent
Chain of ResponsibilityPass requests along a handler chain
CommandEncapsulate requests as objects for queuing/undo
IteratorTraverse collections without exposing internals
MediatorCentralize complex communication between objects
MementoCapture and restore object state
ObserverNotify dependents automatically on state changes
StateAlter behavior when internal state changes
StrategySwap algorithms at runtime
Template MethodDefine algorithm skeleton, let subclasses override steps
VisitorAdd operations to objects without modifying them
See
references/BEHAVIORAL.md
for implementations.
管理算法、职责以及对象间的通信。
模式意图
Chain of Responsibility沿着处理者链传递请求
Command将请求封装为对象,用于排队/撤销操作
Iterator遍历集合而无需暴露内部实现
Mediator集中处理对象间的复杂通信
Memento捕获并恢复对象状态
Observer状态变化时自动通知依赖对象
State内部状态变化时改变行为
Strategy运行时切换算法
Template Method定义算法骨架,让子类重写步骤
Visitor在不修改对象的情况下为对象添加操作
详见
references/BEHAVIORAL.md
中的实现。

Pattern Selection Guide

模式选择指南

ProblemPattern(s)
Need to decouple object creationFactory Method, Abstract Factory
Complex object with many optional fieldsBuilder
Expensive object creation, need copiesPrototype
Global shared resource (config, pool)Singleton
Incompatible third-party interfaceAdapter
Multiple dimensions of variationBridge
Tree structures (files, UI, org charts)Composite
Add features without subclassingDecorator
Simplify complex API surfaceFacade
Thousands of similar objects, memory heavyFlyweight
Lazy loading, access control, cachingProxy
Flexible request processing pipelineChain of Responsibility
Undo/redo, task queues, macrosCommand
Custom collection traversalIterator
Many-to-many object communicationMediator
Snapshots, save/restore stateMemento
Event systems, reactive updatesObserver
Object behavior depends on its stateState
Swappable algorithms (sort, compress, etc)Strategy
Algorithm with fixed steps, variable partsTemplate Method
Operations across heterogeneous objectsVisitor
问题场景适用模式
需要解耦对象创建逻辑Factory Method、Abstract Factory
包含多个可选字段的复杂对象Builder
对象创建成本高,需要复制实例Prototype
全局共享资源(配置、池)Singleton
第三方接口不兼容Adapter
存在多个变化维度Bridge
树形结构(文件、UI、组织结构图)Composite
无需子类化即可添加功能Decorator
简化复杂API接口Facade
大量相似对象,内存占用过高Flyweight
懒加载、访问控制、缓存Proxy
灵活的请求处理管道Chain of Responsibility
撤销/重做、任务队列、宏操作Command
自定义集合遍历逻辑Iterator
对象间多对多通信Mediator
快照、保存/恢复状态Memento
事件系统、响应式更新Observer
对象行为依赖于其状态State
可替换算法(排序、压缩等)Strategy
算法步骤固定,但部分步骤可变Template Method
异构对象间的操作Visitor

Best Practices

最佳实践

DO

建议

  • Choose patterns that solve actual problems you're facing now
  • Prefer composition over inheritance
  • Use dependency injection to decouple components
  • Keep pattern implementations simple — avoid gold-plating
  • Document why a pattern was chosen (not just which one)
  • Consider testability when choosing patterns
  • Combine patterns when appropriate (e.g., Strategy + Factory)
  • 选择能解决当前实际问题的模式
  • 优先使用组合而非继承
  • 使用依赖注入解耦组件
  • 保持模式实现简洁——避免过度设计
  • 记录选择模式的原因(而不只是选择了哪种模式)
  • 选择模式时考虑可测试性
  • 适当组合模式(如Strategy + Factory)

DON'T

避免

  • Apply patterns preemptively for hypothetical future needs
  • Force a pattern where a simple function/object suffices
  • Create unnecessary abstraction layers
  • Use Singleton as a disguised global variable
  • Choose inheritance when composition works better
  • Ignore team familiarity — a simpler pattern everyone knows beats a "better" one nobody understands
  • 为假设的未来需求提前应用模式
  • 在简单函数/对象就能解决问题的情况下强行使用模式
  • 创建不必要的抽象层
  • 将Singleton当作变相的全局变量使用
  • 在组合更合适的情况下选择继承
  • 忽视团队熟悉度——所有人都了解的简单模式胜过没人懂的“更优”模式

SOLID Quick Reference

SOLID原则速查

PrincipleSummaryRelated Patterns
Single ResponsibilityOne class, one reason to changeStrategy, Command, Observer
Open/ClosedOpen for extension, closed for modificationDecorator, Strategy, Template Method
Liskov SubstitutionSubtypes must be substitutable for base typesFactory Method, Abstract Factory
Interface SegregationPrefer small, focused interfacesAdapter, Facade
Dependency InversionDepend on abstractions, not concretionsAll patterns using interfaces/abstract
原则总结相关模式
Single Responsibility一个类,一个变更理由Strategy、Command、Observer
Open/Closed对扩展开放,对修改关闭Decorator、Strategy、Template Method
Liskov Substitution子类必须能替换基类Factory Method、Abstract Factory
Interface Segregation优先使用小而专注的接口Adapter、Facade
Dependency Inversion依赖抽象,而非具体实现所有使用接口/抽象类的模式