mcpField
D
design-patterns

design-patterns

github.com/florianbruniaux开发6.3k65 次安装2 天前更新
代码仓库

关于 design-patterns

面向 TypeScript 和 JavaScript 代码库的只读分析技能,可检测 GoF 模式、针对代码异味提出适配技术栈的建议,并评估实现质量。

主要功能

  1. 01检测 23 种 GoF 模式
  2. 02识别框架和库
  3. 03建议适配技术栈的模式
  4. 04评估实现质量并打分
  5. 05生成 JSON 和 Markdown 报告
  6. 06只分析,不修改文件

适用场景

  1. 01盘点 TypeScript 项目中的模式
  2. 02根据代码异味查找模式
  3. 03审查模式实现
  4. 04比较自定义模式与框架惯用法

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/florianbruniaux/claude-code-ultimate-guide --skill design-patterns

安装后在 Claude Code 中输入/design-patterns确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

checklists/
pattern-evaluation.md
reference/
behavioral.md
creational.md
patterns-index.yaml
structural.md
signatures/
code-smells.yaml
detection-rules.yaml
stack-patterns.yaml

详细介绍

设计模式分析器技能

用途:在 TypeScript/JavaScript 代码库中检测、建议和评估 GoF(四人帮)设计模式,并根据技术栈进行适配。

核心能力

  1. 技术栈检测:识别主要框架/库(React、Angular、NestJS、Vue、Express、RxJS、Redux、ORM)
  2. 模式检测:查找 23 种 GoF 模式的现有实现
  3. 智能建议:推荐用于解决代码异味的模式,并在可行时采用技术栈原生惯用法
  4. 质量评估:根据最佳实践评估模式实现质量

运行模式

模式 1:检测

触发条件:用户请求检测或分析模式 输出:包含已发现模式、置信度分数和技术栈上下文的 JSON 报告

工作流:

1. Stack Detection (package.json, tsconfig.json, framework files)
2. Pattern Search (Glob for candidates -> Grep for signatures -> Read for validation)
3. Classification (native to stack vs custom implementations)
4. Confidence Scoring (0.0-1.0 based on detection rules)
5. JSON Report Generation

调用示例:

/design-patterns detect src/
/design-patterns analyze --format=json
模式 2:建议

触发条件:用户请求模式建议或重构建议 输出:包含按优先级排序的建议和适配技术栈的示例的 Markdown 报告

工作流:

1. Code Smell Detection (switch statements, long parameter lists, global state, etc.)
2. Pattern Matching (map smell -> applicable patterns)
3. Stack Adaptation (prefer native framework patterns over custom implementations)
4. Priority Ranking (impact x feasibility)
5. Markdown Report with Code Examples

调用示例:

/design-patterns suggest src/payment/
/design-patterns refactor --focus=creational
模式 3:评估

触发条件:用户请求评估模式质量 输出:包含各项评估标准分数的 JSON 报告

工作流:

1. Pattern Identification (which pattern is implemented)
2. Criteria Assessment (correctness, testability, SOLID compliance, documentation)
3. Issue Detection (common mistakes, anti-patterns)
4. Scoring (0-10 per criterion)
5. JSON Report with Recommendations

调用示例:

/design-patterns evaluate src/services/singleton.ts
/design-patterns quality --pattern=observer

方法

阶段 1:技术栈检测

来源(按优先级排序):

  1. package.json -> 检查 dependencies 和 devDependencies
  2. 框架专属文件 -> angular.json、next.config.*、nest-cli.json、vite.config.*
  3. tsconfig.json -> 检查 compilerOptions、paths、lib
  4. 文件扩展名 -> 检查是否存在 *.jsx、*.tsx、*.vue

检测规则(来自 signatures/stack-patterns.yaml):

  • React:依赖中包含 react,且存在 *.jsx/*.tsx 文件
  • Angular:包含 @angular/core 和 angular.json
  • NestJS:包含 @nestjs/core 和 nest-cli.json
  • Vue:包含 Vue v3+ 和 *.vue 文件
  • Express:依赖中包含 express,且存在 app.use 模式
  • RxJS:依赖中包含 rxjs,且使用 Observable
  • Redux/Zustand:依赖中包含 redux/zustand,且存在 store 模式
  • Prisma/TypeORM:依赖中包含 prisma/typeorm,且存在 schema 文件

输出:

{
  "stack_detected": {
    "primary": "react",
    "version": "18.2.0",
    "secondary": ["typescript", "zustand", "prisma"],
    "detection_sources": ["package.json", "tsconfig.json", "37 *.tsx files"],
    "confidence": 0.95
  }
}
阶段 2:模式检测

搜索策略:

  1. Glob 阶段:根据命名约定查找候选文件

    • *Singleton*.ts、*Factory*.ts、*Strategy*.ts、*Observer*.ts 等
    • *Manager*.ts、*Builder*.ts、*Adapter*.ts、*Proxy*.ts 等
  2. Grep 阶段:搜索模式特征(来自 signatures/detection-rules.yaml)

    • 主要信号:private constructor、static getInstance()、subscribe()、createXxx() 等
    • 次要信号:接口命名、委托模式、方法签名
  3. 读取阶段:验证模式结构

    • 解析类/接口定义
    • 验证关系(继承、组合、委托)
    • 检查是否为完整的模式实现,而非部分使用

置信度评分:

  • 0.9-1.0:存在所有主要和次要信号,结构完全匹配
  • 0.7-0.89:存在所有主要信号和部分次要信号,仅有轻微偏差
  • 0.5-0.69:存在主要信号,缺少次要验证
  • 0.3-0.49:符合命名约定,但结构证据较弱
  • 0.0-0.29:证据不足,很可能是误报

分类:

  • native:使用技术栈原生特性实现的模式(React Context、Angular Services、NestJS Guards 等)
  • custom:手动实现的 TypeScript 模式
  • library:由第三方库提供的模式(RxJS Subject、Redux Store 等)
阶段 3:代码异味检测

目标异味(来自 signatures/code-smells.yaml):

  1. 按类型切换 -> 策略/工厂模式
  2. 参数列表过长(>4) -> 建造者模式
  3. 访问全局状态 -> 单例(或优先使用 DI)
  4. 针对状态的条件判断重复 -> 状态模式
  5. 通知逻辑分散 -> 观察者模式
  6. 对象创建复杂 -> 工厂/抽象工厂
  7. 与具体类紧密耦合 -> 适配器/桥接
  8. 重复的接口转换 -> 适配器模式
  9. 为添加功能而进行深层嵌套 -> 装饰器模式
  10. 职责过多的大型类 -> 外观模式

检测启发式规则:

  • 搜索 switch (.*type)、switch (.*kind)、switch (.*mode)
  • 统计函数参数:function \w+\([^)]{60,}\)(用于近似判断参数是否超过 4 个)
  • 搜索全局访问:window\.、global\.、process\.env\.\w+(配置文件中除外)
  • 查找状态条件判断:if.*state.*===.*&&.*if.*state.*===
  • 查找通知模式:forEach.*notify、map.*\.emit\(
阶段 4:结合技术栈的建议

适配逻辑(来自 signatures/stack-patterns.yaml):

IF pattern_detected == "custom" AND stack_has_native_equivalent:
  SUGGEST: "Use stack-native pattern instead"
  PROVIDE: Side-by-side comparison (current vs recommended)

ELSE IF code_smell_detected AND pattern_missing:
  IF stack_provides_pattern:
    SUGGEST: Stack-native implementation with examples
  ELSE:
    SUGGEST: Custom TypeScript implementation with best practices

ELSE IF pattern_implemented_incorrectly:
  PROVIDE: Refactoring steps to fix anti-patterns

适配示例:

模式技术栈原生替代方案建议
单例ReactContext API + Provider使用 createContext(),而不是 getInstance()
观察者AngularRxJS Subject/BehaviorSubject使用内置的 Observables,而不是自定义实现
装饰器NestJS@Injectable() 装饰器 + Interceptors使用框架拦截器
策略Vue 3Composition API composables使用 ref() + composables,而不是类
责任链Express中间件(app.use())使用 Express 中间件链
命令ReduxAction creators + reducers使用 Redux actions,而不是自定义命令对象
阶段 5:质量评估

评估标准(来自 checklists/pattern-evaluation.md):

  1. 正确性(0-10):是否符合规范模式的结构?
  2. 可测试性(0-10):是否能轻松模拟或替代依赖项?
  3. 单一职责(0-10):是否只做一件事?
  4. 开闭原则(0-10):是否无需修改即可扩展?
  5. 文档(0-10):意图是否清晰,命名是否具有描述性?

评分指南:

  • 9-10:典范,可作为参考的实现
  • 7-8:良好,仍有小幅改进空间
  • 5-6:可接受,但有值得解决的问题
  • 3-4:存在问题,需要进行重大重构
  • 0-2:不正确或存在严重缺陷

问题检测:

  • 硬编码依赖(在 getInstance 内使用 new 的单例)
  • 上帝类(职责过多)
  • 抽象泄漏(暴露内部结构)
  • 缺少错误处理
  • 命名不佳(使用 Strategy1、Strategy2,而非描述性名称)

输出格式

检测模式(JSON)
{
  "metadata": {
    "scan_date": "2026-01-21T10:30:00Z",
    "scope": "src/",
    "files_scanned": 147,
    "execution_time_ms": 2341
  },
  "stack_detected": {
    "primary": "react",
    "version": "18.2.0",
    "secondary": ["typescript", "zustand", "prisma"],
    "detection_sources": ["package.json", "tsconfig.json", "37 *.tsx files"],
    "confidence": 0.95
  },
  "patterns_found": {
    "singleton": [
      {
        "file": "src/lib/api-client.ts",
        "lines": "5-28",
        "confidence": 0.85,
        "type": "custom",
        "signals": ["private constructor", "static getInstance", "private static instance"],
        "note": "Consider using React Context instead for better testability"
      }
    ],
    "observer": [
      {
        "file": "src/hooks/useAuth.ts",
        "lines": "12-45",
        "confidence": 0.92,
        "type": "native",
        "implementation": "React useState + useEffect",
        "note": "Correctly using React's built-in observer pattern"
      }
    ],
    "factory": [
      {
        "file": "src/services/notification-factory.ts",
        "lines": "8-67",
        "confidence": 0.78,
        "type": "custom",
        "signals": ["createNotification method", "type discrimination", "returns interface"]
      }
    ]
  },
  "summary": {
    "total_patterns": 7,
    "native_to_stack": 4,
    "custom_implementations": 3,
    "by_category": {
      "creational": 2,
      "structural": 3,
      "behavioral": 2
    },
    "by_confidence": {
      "high": 5,
      "medium": 2,
      "low": 0
    }
  },
  "recommendations": [
    "Consider replacing custom Singleton (api-client.ts) with React Context for better DI",
    "Review Factory pattern (notification-factory.ts) - could be simplified with strategy pattern"
  ]
}
建议模式(Markdown)
# Design Pattern Suggestions

**Scope**: `src/payment/`
**Stack**: React 18 + TypeScript + Stripe
**Date**: 2026-01-21

---

## High Priority

### 1. Strategy Pattern: `src/payment/processor.ts:45-89`

**Code Smell**: Switch statement on payment type (4 cases, 78 lines)

**Current Implementation** (lines 52-87):
```typescript
switch (paymentType) {
  case 'credit':
    // 20 lines of credit card logic
    break;
  case 'paypal':
    // 15 lines of PayPal logic
    break;
  case 'crypto':
    // 18 lines of crypto logic
    break;
  case 'bank':
    // 12 lines of bank transfer logic
    break;
}

推荐方案(适配 React 的策略模式):

// Define strategy interface
interface PaymentStrategy {
  process: (amount: number) => Promise<PaymentResult>;
}

// Custom hooks as strategies
const useCreditPayment = (): PaymentStrategy => ({
  process: async (amount) => { /* credit logic */ }
});

const usePaypalPayment = (): PaymentStrategy => ({
  process: async (amount) => { /* PayPal logic */ }
});

// Strategy selection hook
const usePaymentStrategy = (type: PaymentType): PaymentStrategy => {
  const strategies = {
    credit: useCreditPayment(),
    paypal: usePaypalPayment(),
    crypto: useCryptoPayment(),
    bank: useBankPayment(),
  };
  return strategies[type];
};

// Usage in component
const PaymentForm = ({ type }: Props) => {
  const strategy = usePaymentStrategy(type);
  const handlePay = () => strategy.process(amount);
  // ...
};

影响:

  • 复杂度:将圈复杂度从 12 降至 2
  • 可扩展性:新增支付方式只需添加新的 hook,无需修改现有代码
  • 可测试性:每个策略 hook 都可以单独测试
  • 工作量:约 2 小时(将逻辑提取到 hooks 中,并添加测试)

中优先级

2. 观察者模式:src/cart/CartManager.ts:23-156

代码异味:手动通知逻辑分散在 8 个方法中

当前方案:通过手动循环调用更新函数 建议方案:使用 Zustand store(已在依赖项中)

// Instead of custom observer:
import create from 'zustand';

interface CartStore {
  items: CartItem[];
  addItem: (item: CartItem) => void;
  removeItem: (id: string) => void;
  // Zustand automatically notifies subscribers
}

export const useCartStore = create<CartStore>((set) => ({
  items: [],
  addItem: (item) => set((state) => ({ items: [...state.items, item] })),
  removeItem: (id) => set((state) => ({ items: state.items.filter(i => i.id !== id) })),
}));

// Components auto-subscribe:
const CartDisplay = () => {
  const items = useCartStore((state) => state.items);
  // Re-renders automatically on cart changes
};

影响:

  • 代码行数:从 156 行减少到约 25 行
  • 贴合技术栈:使用现有的 Zustand 依赖项
  • 可测试性:Zustand store 易于测试
  • 工作量:约 1.5 小时

摘要

  • 建议总数:4
  • 高优先级:2(策略、观察者)
  • 中优先级:2(建造者、外观)
  • 预计总工作量:约 6 小时
  • 主要收益:降低复杂度、提升可测试性、采用符合技术栈惯例的写法

### Evaluation mode (JSON)

```json
{
  "file": "src/services/config-singleton.ts",
  "pattern": "singleton",
  "lines": "5-34",
  "scores": {
    "correctness": 8,
    "testability": 4,
    "single_responsibility": 9,
    "open_closed": 7,
    "documentation": 6,
    "overall": 6.8
  },
  "details": {
    "correctness": {
      "score": 8,
      "rationale": "Implements singleton structure correctly with private constructor and static getInstance",
      "issues": ["Missing thread-safety consideration (not critical in JS single-threaded context)"]
    },
    "testability": {
      "score": 4,
      "rationale": "Hard to mock or reset instance in tests",
      "issues": [
        "No reset method for test isolation",
        "Static instance makes dependency injection impossible",
        "Tests must run in specific order or share state"
      ],
      "suggestions": [
        "Add resetInstance() method for tests (with appropriate guards)",
        "Consider using dependency injection instead"
      ]
    },
    "single_responsibility": {
      "score": 9,
      "rationale": "Focuses solely on configuration management",
      "issues": []
    },
    "open_closed": {
      "score": 7,
      "rationale": "Configuration can be extended but requires modification for new sources",
      "suggestions": ["Consider strategy pattern for configuration sources"]
    },
    "documentation": {
      "score": 6,
      "rationale": "Has JSDoc but missing rationale for singleton choice",
      "suggestions": ["Document why singleton is chosen over DI", "Add usage examples"]
    }
  },
  "recommendations": [
    {
      "priority": "high",
      "suggestion": "Add test-friendly reset mechanism or refactor to use DI",
      "rationale": "Current implementation makes testing difficult"
    },
    {
      "priority": "medium",
      "suggestion": "Document singleton rationale in JSDoc",
      "rationale": "Team members should understand why global state is necessary here"
    }
  ]
}

约束与指南

只读分析
  • 不做修改:此技能仅进行分析并提出建议,不会修改代码
  • 不创建文件:不会生成重构后的代码文件
  • 由用户决定:所有建议在实施前都需要获得用户明确批准
语言侧重
  • 主要支持:TypeScript(.ts、.tsx)
  • 次要支持:JavaScript(.js、.jsx)
  • 不支持:其他语言(Python、Java、C#)
模式覆盖范围
  • 创建型(5 种):Singleton、Factory Method、Abstract Factory、Builder、Prototype
  • 结构型(7 种):Adapter、Bridge、Composite、Decorator、Facade、Flyweight、Proxy
  • 行为型(11 种):Chain of Responsibility、Command、Iterator、Mediator、Memento、Observer、State、Strategy、Template Method、Visitor、Interpreter
性能注意事项
  • 大型代码库(>500 个文件):使用 --scope 将扫描范围限制在指定目录
  • 并行搜索:每种模式的 Grep 搜索都会独立运行
  • 缓存:每个会话都会缓存技术栈检测结果,以避免重复读取 package.json

使用示例

基本检测
# Detect all patterns in src/
/design-patterns detect src/

# Detect only creational patterns
/design-patterns detect src/ --category=creational

# Focus on specific pattern
/design-patterns detect src/ --pattern=singleton
针对性建议
# Get suggestions for payment module
/design-patterns suggest src/payment/

# Focus on specific smell
/design-patterns suggest src/ --smell=switch-on-type

# High priority only
/design-patterns suggest src/ --priority=high
质量评估
# Evaluate specific file
/design-patterns evaluate src/services/api-client.ts

# Evaluate all singletons
/design-patterns evaluate src/ --pattern=singleton

# Full quality report
/design-patterns evaluate src/ --detailed

与其他技能集成

此技能可由以下技能继承:

  • refactoring-specialist.md:为重构提供模式知识
  • code-reviewer.md:在审查流程中加入模式检测
  • architecture-advisor.md:利用模式用法为架构决策提供参考

参考文件

  • reference/patterns-index.yaml:包含 23 种模式及其元数据的机器可读索引
  • reference/creational.md:创建型模式文档
  • reference/structural.md:结构型模式文档
  • reference/behavioral.md:行为型模式文档
  • signatures/detection-rules.yaml:用于检测的正则表达式模式和启发式规则
  • signatures/code-smells.yaml:代码异味与适用模式之间的映射
  • signatures/stack-patterns.yaml:技术栈检测规则和原生模式等效项
  • checklists/pattern-evaluation.md:质量评估标准和评分指南

版本

技能版本:1.0.0 模式覆盖范围:23 种 GoF 模式 支持的技术栈:8 种(React、Angular、NestJS、Vue、Express、RxJS、Redux/Zustand、ORM) 最后更新:2026-01-21

评论

支持 Markdown