modularity-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseModularity Patterns
模块化模式
Apply these patterns when designing or refactoring code for modularity, extensibility, and decoupling.
在设计或重构代码以实现模块化、可扩展性和解耦时,可应用以下模式。
Trigger Conditions
适用场景
Apply this skill when:
- Designing plugin or extension architectures
- Reducing coupling between components
- Improving testability through dependency management
- Creating flexible, configurable systems
- Separating cross-cutting concerns
在以下场景中应用此技能:
- 设计插件或扩展架构
- 降低组件间的耦合性
- 通过依赖管理提升可测试性
- 创建灵活、可配置的系统
- 分离横切关注点
Select the Right Pattern
选择合适的模式
| Problem | Apply These Patterns |
|---|---|
| Hard-coded dependencies | DI, IoC, Service Locator, SAM |
| Need runtime extensions | Plugin, Microkernel, Extension Points |
| Swappable algorithms | Strategy, Abstract Factory |
| Additive behavior | Decorator, Chain of Responsibility, SAM |
| Feature coupling | Package by Feature |
| Scattered concerns | AOP, Interceptors, Mixins, SAM |
| Temporal coupling | Observer, Event Bus, Event Sourcing, SAM |
| Read/write optimization | CQRS |
| Deployment flexibility | Feature Toggles, Microservices |
| 问题 | 适用模式 |
|---|---|
| 硬编码依赖 | DI, IoC, Service Locator, SAM |
| 需要运行时扩展 | Plugin, Microkernel, Extension Points |
| 可替换算法 | Strategy, Abstract Factory |
| 增量式行为扩展 | Decorator, Chain of Responsibility, SAM |
| 功能耦合 | Package by Feature |
| 分散的关注点 | AOP, Interceptors, Mixins, SAM |
| 时序耦合 | Observer, Event Bus, Event Sourcing, SAM |
| 读写优化 | CQRS |
| 部署灵活性 | Feature Toggles, Microservices |
Implementation Checklist
实施检查清单
When applying any modularity pattern:
- Define clear interfaces - Contracts before implementations
- Minimize surface area - Expose only what's necessary
- Depend on abstractions - Not concrete implementations
- Favor composition - Over inheritance
- Isolate side effects - Push to boundaries
- Make dependencies explicit - Visible in signatures
- Design for substitution - Any implementation satisfying contract works
- Consider lifecycle - Creation, configuration, destruction
- Plan for versioning - APIs evolve, maintain compatibility
- Test boundaries - Verify contracts, mock implementations
应用任何模块化模式时:
- 定义清晰的接口 - 先有契约,后有实现
- 最小化暴露面 - 仅暴露必要内容
- 依赖抽象而非具体实现
- 优先组合而非继承
- 隔离副作用 - 将副作用推送到边界
- 明确依赖关系 - 在签名中清晰可见
- 为替换设计 - 任何满足契约的实现都可正常工作
- 考虑生命周期 - 创建、配置、销毁
- 规划版本控制 - API会演进,需保持兼容性
- 测试边界 - 验证契约,模拟实现
Pattern Reference
模式参考
Inversion Patterns
反转模式
Dependency Injection (DI) - Provide dependencies externally rather than creating internally.
- Constructor injection (preferred, immutable)
- Setter injection (optional dependencies)
- Interface injection (framework-driven)
Inversion of Control (IoC) - Let framework control flow, calling your code. Use IoC containers (Spring, Guice, .NET DI) to manage object lifecycles and wiring.
Service Locator - Query central registry for dependencies at runtime. Achieves decoupling but hides dependencies. Prefer DI for explicitness.
依赖注入(DI) - 从外部提供依赖,而非在内部创建。
- 构造函数注入(推荐,不可变)
- Setter注入(可选依赖)
- 接口注入(框架驱动)
控制反转(IoC) - 由框架控制流程,调用你的代码。使用IoC容器(Spring、Guice、.NET DI)管理对象生命周期和依赖注入。
服务定位器 - 在运行时查询中央注册表获取依赖。实现了解耦但隐藏了依赖关系。优先使用DI以保证明确性。
Plugin & Extension Architectures
插件与扩展架构
Plugin Pattern - Load and integrate external code at runtime via defined contracts.
- Discovery: directory scanning, manifests, registries
- Lifecycle: load, initialize, unload
- Isolation: classloaders, processes, sandboxes
- Versioning: API compatibility
Microkernel Architecture - Build minimal core with all domain functionality in plugins. Examples: VS Code, Eclipse IDE.
Extension Points & Registry - Define multiple specific extension points rather than single plugin interface. Extensions declare which points they extend.
插件模式 - 通过定义的契约在运行时加载并集成外部代码。
- 发现机制:目录扫描、清单、注册表
- 生命周期:加载、初始化、卸载
- 隔离:类加载器、进程、沙箱
- 版本控制:API兼容性
微内核架构 - 构建最小化核心,所有领域功能都在插件中实现。示例:VS Code、Eclipse IDE。
扩展点与注册表 - 定义多个特定的扩展点,而非单一插件接口。扩展需声明其要扩展的点。
Structural Composition
结构型组合
Strategy Pattern - Encapsulate interchangeable algorithms behind common interface.
Context → Strategy Interface → Concrete StrategiesUse for runtime behavioral swapping (sorting, validation, pricing).
Decorator Pattern - Wrap objects to add behavior without modification.
Component → Decorator → Decorator → Concrete ComponentUse for composable behavior chains (logging, caching, validation).
Composite Pattern - Treat individuals and compositions uniformly via shared interface. Use for tree structures, UI hierarchies, file systems.
Chain of Responsibility - Create pipeline of handlers where each processes or forwards. Use for middleware stacks, request processing pipelines.
Bridge Pattern - Separate abstraction from implementation hierarchies. Use to prevent subclass explosion with multiple varying dimensions.
策略模式 - 将可互换的算法封装在通用接口后。
Context → Strategy Interface → Concrete Strategies用于运行时行为切换(排序、验证、定价等)。
装饰器模式 - 包装对象以添加行为,无需修改原对象。
Component → Decorator → Decorator → Concrete Component用于可组合的行为链(日志、缓存、验证等)。
组合模式 - 通过共享接口统一处理单个对象和组合对象。用于树结构、UI层级、文件系统等。
责任链模式 - 创建处理程序管道,每个处理程序要么处理请求要么转发。用于中间件栈、请求处理管道等。
桥接模式 - 将抽象与实现层次分离。用于避免因多个变化维度导致的子类爆炸。
Module Boundaries
模块边界
Module Pattern - Encapsulate private state, expose public interface. Modern implementations: ES Modules, CommonJS, Java 9 modules.
Facade Pattern - Provide simplified interface to complex subsystem. Use to establish clean module boundaries.
Package Organization
- By Layer: Group controllers, repositories, services separately
- By Feature: Group everything for "orders" together (preferred for modularity)
模块模式 - 封装私有状态,暴露公共接口。现代实现:ES Modules、CommonJS、Java 9模块。
外观模式 - 为复杂子系统提供简化接口。用于建立清晰的模块边界。
包组织方式
- 按层分组:将控制器、仓库、服务分开分组
- 按功能分组:将与“订单”相关的所有内容放在一起(推荐用于模块化)
Event-Driven Decoupling
事件驱动解耦
Observer Pattern - Implement publish-subscribe where subjects notify observers without knowing them.
Event Bus / Message Broker - Enable system-wide pub-sub with fully decoupled publishers and subscribers. Add behaviors by adding subscribers without publisher changes.
Event Sourcing - Store state changes as event sequence, not snapshots. Enable new projections via event replay; new behaviors react to stream.
CQRS - Separate read and write models.
Commands → Write Model (validation, rules, persistence)
Queries → Read Model (optimized for reading)观察者模式 - 实现发布-订阅机制,主题通知观察者而无需了解观察者的具体信息。
事件总线/消息代理 - 实现系统级别的发布-订阅,发布者和订阅者完全解耦。通过添加订阅者即可新增行为,无需修改发布者。
事件溯源 - 将状态变化存储为事件序列,而非快照。通过重放事件生成新的投影;新行为可响应事件流。
CQRS - 分离读模型与写模型。
Commands → Write Model (验证、规则、持久化)
Queries → Read Model (针对读取优化)Cross-Cutting Concerns
横切关注点
Aspect-Oriented Programming (AOP) - Modularize scattered concerns (logging, security, transactions). Define pointcuts (where) and advice (what).
Interceptors & Middleware - Explicitly wrap method calls or request pipelines. Less magical than AOP, more traceable.
Mixins & Traits - Compose behaviors from multiple sources without deep inheritance. Examples: Scala traits, Rust traits, TypeScript intersections.
面向切面编程(AOP) - 将分散的关注点(日志、安全、事务)模块化。定义切入点(何处应用)和通知(执行什么)。
拦截器与中间件 - 显式包装方法调用或请求管道。比AOP更直观,更易于追踪。
Mixin与Trait - 从多个来源组合行为,无需深度继承。示例:Scala traits、Rust traits、TypeScript交叉类型。
Configuration Patterns
配置模式
Feature Toggles - Decouple deployment from release by shipping new code behind flags. Enables trunk-based development, A/B testing, gradual rollouts.
Strategy Configuration - Externalize algorithmic choices to configuration files.
Convention over Configuration - Reduce wiring through established defaults and naming conventions.
功能开关 - 通过标记隐藏新代码,实现部署与发布解耦。支持主干开发、A/B测试、逐步发布。
策略配置 - 将算法选择外部化到配置文件中。
约定优于配置 - 通过既定的默认值和命名约定减少配置工作。
Component Models
组件模型
Component-Based Architecture - Build self-contained components with defined interfaces managing own state. Examples: React, Vue, server-side component frameworks.
Entity-Component-System (ECS) - Separate identity (entities), data (components), behavior (systems). Use for game development, highly dynamic systems.
Service-Oriented / Microservices - Apply component thinking at system level with process isolation boundaries.
基于组件的架构 - 构建自包含组件,组件拥有定义好的接口并管理自身状态。示例:React、Vue、服务端组件框架。
实体-组件-系统(ECS) - 将标识(实体)、数据(组件)、行为(系统)分离。用于游戏开发、高度动态的系统。
面向服务/微服务 - 在系统层面应用组件思想,通过进程隔离边界实现。
Creational Patterns
创建型模式
Registry Pattern - Maintain collection of implementations keyed by type/name, queried at runtime.
Abstract Factory - Create families of related objects without specifying concrete classes.
Prototype Pattern - Create objects by cloning prototypes, avoiding direct class instantiation.
注册器模式 - 维护按类型/名称键控的实现集合,在运行时查询。
抽象工厂 - 创建相关对象家族,无需指定具体类。
原型模式 - 通过克隆原型创建对象,避免直接实例化类。
SAM Pattern (State-Action-Model)
SAM模式(State-Action-Model)
Functional decomposition for reactive systems:
- State: Pure representation of current state
- Action: Pure functions proposing state changes
- Model: State acceptor enforcing business rules
Loop: View renders State → Actions propose → Model accepts/rejects → State updates.
Provides natural boundaries between representation, proposals, and validation.
响应式系统的函数式分解:
- State(状态): 当前状态的纯表示
- Action(动作): 提议状态变更的纯函数
- Model(模型): 接受状态并执行业务规则的组件
循环流程:视图渲染状态 → 动作提议变更 → 模型接受/拒绝 → 状态更新。
在表示层、提议层和验证层之间提供天然的边界。