design-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Design Patterns Analyzer Skill

设计模式分析器Skill

Purpose: Detect, suggest, and evaluate Gang of Four (GoF) design patterns in TypeScript/JavaScript codebases with stack-aware adaptations.
用途:检测、建议并评估TypeScript/JavaScript代码库中的Gang of Four(GoF)设计模式,同时适配对应技术栈。

Core Capabilities

核心功能

  1. Stack Detection: Identify primary framework/library (React, Angular, NestJS, Vue, Express, RxJS, Redux, ORMs)
  2. Pattern Detection: Find existing implementations of 23 GoF patterns
  3. Smart Suggestions: Recommend patterns to fix code smells, using stack-native idioms when available
  4. Quality Evaluation: Assess pattern implementation quality against best practices
  1. 技术栈检测:识别主要框架/库(React、Angular、NestJS、Vue、Express、RxJS、Redux、ORM)
  2. 模式检测:查找23种GoF模式的现有实现
  3. 智能建议:推荐可修复代码异味的模式,优先使用技术栈原生语法
  4. 质量评估:对照最佳实践评估模式实现的质量

Operating Modes

运行模式

Mode 1: Detection

模式1:检测

Trigger: User requests pattern detection or analysis Output: JSON report of patterns found with confidence scores and stack context
Workflow:
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
Example invocation:
/design-patterns detect src/
/design-patterns analyze --format=json
触发条件:用户请求模式检测或分析 输出:包含已发现模式、置信度评分及技术栈上下文的JSON报告
工作流程
1. 技术栈检测(package.json、tsconfig.json、框架文件)
2. 模式搜索(全局匹配候选文件 → 匹配特征签名 → 读取文件验证)
3. 分类(技术栈原生实现 vs 自定义实现)
4. 置信度评分(基于检测规则给出0.0-1.0的分数)
5. 生成JSON报告
调用示例
/design-patterns detect src/
/design-patterns analyze --format=json

Mode 2: Suggestion

模式2:建议

Trigger: User requests pattern suggestions or refactoring advice Output: Markdown report with prioritized suggestions and stack-adapted examples
Workflow:
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 × feasibility)
5. Markdown Report with Code Examples
Example invocation:
/design-patterns suggest src/payment/
/design-patterns refactor --focus=creational
触发条件:用户请求模式建议或重构指导 输出:包含优先级建议及适配技术栈示例的Markdown报告
工作流程
1. 代码异味检测(switch语句、长参数列表、全局状态等)
2. 模式匹配(将异味映射为适用的模式)
3. 技术栈适配(优先使用框架原生模式而非自定义实现)
4. 优先级排序(影响程度 × 实现可行性)
5. 生成带代码示例的Markdown报告
调用示例
/design-patterns suggest src/payment/
/design-patterns refactor --focus=creational

Mode 3: Evaluation

模式3:评估

Trigger: User requests pattern quality assessment Output: JSON report with scores per evaluation criterion
Workflow:
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
Example invocation:
/design-patterns evaluate src/services/singleton.ts
/design-patterns quality --pattern=observer
触发条件:用户请求模式质量评估 输出:包含各评估标准得分的JSON报告
工作流程
1. 模式识别(确定当前实现的是哪种模式)
2. 标准评估(正确性、可测试性、SOLID合规性、文档完整性)
3. 问题检测(常见错误、反模式)
4. 评分(每个标准0-10分)
5. 生成带改进建议的JSON报告
调用示例
/design-patterns evaluate src/services/singleton.ts
/design-patterns quality --pattern=observer

Methodology

方法论

Phase 1: Stack Detection

阶段1:技术栈检测

Sources (in priority order):
  1. package.json
    → Check dependencies and devDependencies
  2. Framework-specific files →
    angular.json
    ,
    next.config.*
    ,
    nest-cli.json
    ,
    vite.config.*
  3. tsconfig.json
    → Check compilerOptions, paths, lib
  4. File extensions →
    *.jsx
    ,
    *.tsx
    ,
    *.vue
    presence
Detection Rules (from
signatures/stack-patterns.yaml
):
  • React:
    react
    in deps +
    *.jsx/*.tsx
    files
  • Angular:
    @angular/core
    +
    angular.json
  • NestJS:
    @nestjs/core
    +
    nest-cli.json
  • Vue:
    vue
    v3+ +
    *.vue
    files
  • Express:
    express
    in deps +
    app.use
    patterns
  • RxJS:
    rxjs
    in deps + Observable usage
  • Redux/Zustand:
    redux
    /
    zustand
    in deps + store patterns
  • Prisma/TypeORM:
    prisma
    /
    typeorm
    in deps + schema files
Output:
json
{
  "stack_detected": {
    "primary": "react",
    "version": "18.2.0",
    "secondary": ["typescript", "zustand", "prisma"],
    "detection_sources": ["package.json", "tsconfig.json", "37 *.tsx files"],
    "confidence": 0.95
  }
}
数据源(优先级排序):
  1. package.json
    → 检查依赖项和开发依赖项
  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:依赖中包含v3+版本的
    vue
    + 存在
    *.vue
    文件
  • Express:依赖中包含
    express
    + 存在
    app.use
    模式
  • RxJS:依赖中包含
    rxjs
    + 存在Observable用法
  • Redux/Zustand:依赖中包含
    redux
    /
    zustand
    + 存在store模式
  • Prisma/TypeORM:依赖中包含
    prisma
    /
    typeorm
    + 存在schema文件
输出示例
json
{
  "stack_detected": {
    "primary": "react",
    "version": "18.2.0",
    "secondary": ["typescript", "zustand", "prisma"],
    "detection_sources": ["package.json", "tsconfig.json", "37 *.tsx files"],
    "confidence": 0.95
  }
}

Phase 2: Pattern Detection

阶段2:模式检测

Search Strategy:
  1. Glob Phase: Find candidate files by naming convention
    • *Singleton*.ts
      ,
      *Factory*.ts
      ,
      *Strategy*.ts
      ,
      *Observer*.ts
      , etc.
    • *Manager*.ts
      ,
      *Builder*.ts
      ,
      *Adapter*.ts
      ,
      *Proxy*.ts
      , etc.
  2. Grep Phase: Search for pattern signatures (from
    signatures/detection-rules.yaml
    )
    • Primary signals:
      private constructor
      ,
      static getInstance()
      ,
      subscribe()
      ,
      createXxx()
      , etc.
    • Secondary signals: Interface naming, delegation patterns, method signatures
  3. Read Phase: Validate pattern structure
    • Parse class/interface definitions
    • Verify relationships (inheritance, composition, delegation)
    • Check for complete pattern implementation vs partial usage
Confidence Scoring:
  • 0.9-1.0: All primary + secondary signals present, structure matches exactly
  • 0.7-0.89: All primary signals + some secondary, minor deviations
  • 0.5-0.69: Primary signals present, missing secondary validation
  • 0.3-0.49: Naming convention matches, weak structural evidence
  • 0.0-0.29: Insufficient evidence, likely false positive
Classification:
  • native
    : Pattern implemented using stack-native features (React Context, Angular Services, NestJS Guards, etc.)
  • custom
    : Manual TypeScript implementation
  • library
    : Third-party library providing pattern (RxJS Subject, Redux Store, etc.)
搜索策略
  1. 全局匹配阶段:通过命名规则查找候选文件
    • *Singleton*.ts
      *Factory*.ts
      *Strategy*.ts
      *Observer*.ts
    • *Manager*.ts
      *Builder*.ts
      *Adapter*.ts
      *Proxy*.ts
  2. 特征匹配阶段:搜索模式特征签名(来自
    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等)

Phase 3: Code Smell Detection

阶段3:代码异味检测

Target Smells (from
signatures/code-smells.yaml
):
  1. Switch on Type → Strategy/Factory pattern
  2. Long Parameter List (>4) → Builder pattern
  3. Global State Access → Singleton (or preferably DI)
  4. Duplicated Conditionals on State → State pattern
  5. Scattered Notification Logic → Observer pattern
  6. Complex Object Creation → Factory/Abstract Factory
  7. Tight Coupling to Concrete Classes → Adapter/Bridge
  8. Repetitive Interface Conversions → Adapter pattern
  9. Deep Nesting for Feature Addition → Decorator pattern
  10. Large Class with Many Responsibilities → Facade pattern
Detection Heuristics:
  • Grep for
    switch (.*type)
    ,
    switch (.*kind)
    ,
    switch (.*mode)
  • Count function parameters:
    function \w+\([^)]{60,}\)
    (approximation for >4 params)
  • Search for global access:
    window\.
    ,
    global\.
    ,
    process\.env\.\w+
    (not in config files)
  • Find state conditionals:
    if.*state.*===.*&&.*if.*state.*===
  • Find notification patterns:
    forEach.*notify
    ,
    map.*\.emit\(
目标异味(来自
signatures/code-smells.yaml
):
  1. 基于类型的Switch语句 → 策略/工厂模式
  2. 长参数列表(>4个) → 建造者模式
  3. 全局状态访问 → 单例(或优先使用依赖注入)
  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\(

Phase 4: Stack-Aware Suggestions

阶段4:适配技术栈的建议

Adaptation Logic (from
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
Example Adaptations:
PatternStackNative AlternativeRecommendation
SingletonReactContext API + ProviderUse
createContext()
instead of
getInstance()
ObserverAngularRxJS Subject/BehaviorSubjectUse built-in Observables, not custom implementation
DecoratorNestJS@Injectable() decorators + InterceptorsUse framework interceptors
StrategyVue 3Composition API composablesUse
ref()
+ composables instead of classes
Chain of ResponsibilityExpressMiddleware (
app.use()
)
Use Express middleware chain
CommandReduxAction creators + reducersUse Redux actions, not custom command objects
适配逻辑(来自
signatures/stack-patterns.yaml
):
IF pattern_detected == "custom" AND stack_has_native_equivalent:
  SUGGEST: "改用技术栈原生模式"
  PROVIDE: 对比示例(当前实现 vs 推荐实现)

ELSE IF code_smell_detected AND pattern_missing:
  IF stack_provides_pattern:
    SUGGEST: 带示例的技术栈原生实现
  ELSE:
    SUGGEST: 遵循最佳实践的自定义TypeScript实现

ELSE IF pattern_implemented_incorrectly:
  PROVIDE: 修复反模式的重构步骤
适配示例
模式技术栈原生替代方案建议
单例ReactContext API + Provider使用
createContext()
替代
getInstance()
观察者AngularRxJS Subject/BehaviorSubject使用内置Observable,而非自定义实现
装饰器NestJS@Injectable()装饰器 + Interceptors使用框架拦截器
策略Vue 3Composition API组合式函数使用
ref()
+ 组合式函数替代类
职责链Express中间件(
app.use()
使用Express中间件链
命令ReduxAction创建器 + reducer使用Redux动作,而非自定义命令对象

Phase 5: Quality Evaluation

阶段5:质量评估

Criteria (from
checklists/pattern-evaluation.md
):
  1. Correctness (0-10): Does it match the canonical pattern structure?
  2. Testability (0-10): Can dependencies be mocked/stubbed easily?
  3. Single Responsibility (0-10): Does it do one thing only?
  4. Open/Closed Principle (0-10): Extensible without modification?
  5. Documentation (0-10): Clear intent, descriptive naming?
Scoring Guidelines:
  • 9-10: Exemplary, reference-quality implementation
  • 7-8: Good, minor improvements possible
  • 5-6: Acceptable, notable issues to address
  • 3-4: Problematic, significant refactoring needed
  • 0-2: Incorrect or severely flawed
Issue Detection:
  • Hard-coded dependencies (Singleton with new inside getInstance)
  • God classes (too many responsibilities)
  • Leaky abstractions (exposing internal structure)
  • Missing error handling
  • Poor naming (Strategy1, Strategy2 instead of descriptive names)
评估标准(来自
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而非描述性名称)

Output Formats

输出格式

Detection Mode (JSON)

检测模式(JSON)

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"
  ]
}
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": "建议改用React Context以提升可测试性"
      }
    ],
    "observer": [
      {
        "file": "src/hooks/useAuth.ts",
        "lines": "12-45",
        "confidence": 0.92,
        "type": "native",
        "implementation": "React useState + useEffect",
        "note": "正确使用React内置的观察者模式"
      }
    ],
    "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": [
    "考虑将自定义单例(api-client.ts)替换为React Context以优化依赖注入",
    "检查工厂模式(notification-factory.ts)——可通过策略模式简化实现"
  ]
}

Suggestion Mode (Markdown)

建议模式(Markdown)

markdown
undefined
markdown
undefined

Design Pattern Suggestions

设计模式建议

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

范围
src/payment/
技术栈:React 18 + TypeScript + Stripe 日期:2026-01-21

High Priority

高优先级

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

1. 策略模式 →
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;
}
Recommended (React-adapted Strategy):
typescript
// 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);
  // ...
};
Impact:
  • Complexity: Reduces cyclomatic complexity from 12 to 2
  • Extensibility: New payment methods = new hook, no modification to existing code
  • Testability: Each strategy hook can be tested in isolation
  • Effort: ~2 hours (extract logic into hooks, add tests)

代码异味:基于支付类型的switch语句(4个分支,78行代码)
当前实现(第52-87行):
typescript
switch (paymentType) {
  case 'credit':
    // 20行信用卡逻辑
    break;
  case 'paypal':
    // 15行PayPal逻辑
    break;
  case 'crypto':
    // 18行加密货币逻辑
    break;
  case 'bank':
    // 12行银行转账逻辑
    break;
}
推荐(适配React的策略模式)
typescript
// 定义策略接口
interface PaymentStrategy {
  process: (amount: number) => Promise<PaymentResult>;
}

// 自定义Hook作为策略
const useCreditPayment = (): PaymentStrategy => ({
  process: async (amount) => { /* 信用卡逻辑 */ }
});

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

// 策略选择Hook
const usePaymentStrategy = (type: PaymentType): PaymentStrategy => {
  const strategies = {
    credit: useCreditPayment(),
    paypal: usePaypalPayment(),
    crypto: useCryptoPayment(),
    bank: useBankPayment(),
  };
  return strategies[type];
};

// 在组件中使用
const PaymentForm = ({ type }: Props) => {
  const strategy = usePaymentStrategy(type);
  const handlePay = () => strategy.process(amount);
  // ...
};
影响
  • 复杂度:圈复杂度从12降低至2
  • 可扩展性:新增支付方式只需添加新Hook,无需修改现有代码
  • 可测试性:每个策略Hook可独立测试
  • 工作量:约2小时(将逻辑提取到Hook,添加测试)

Medium Priority

中优先级

2. Observer Pattern →
src/cart/CartManager.ts:23-156

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

Code Smell: Manual notification logic scattered across 8 methods
Current: Manual loops calling update functions Recommended: Use Zustand store (already in dependencies)
typescript
// 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
};
Impact:
  • LOC: Reduces from 156 to ~25 lines
  • Stack-native: Uses existing Zustand dependency
  • Testability: Zustand stores are easily tested
  • Effort: ~1.5 hours

代码异味:手动通知逻辑分散在8个方法中
当前实现:手动循环调用更新函数 推荐方案:使用已依赖的Zustand store
typescript
// 替代自定义观察者:
import create from 'zustand';

interface CartStore {
  items: CartItem[];
  addItem: (item: CartItem) => void;
  removeItem: (id: string) => void;
  // Zustand自动通知订阅者
}

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) })),
}));

// 组件自动订阅:
const CartDisplay = () => {
  const items = useCartStore((state) => state.items);
  // 购物车变化时自动重新渲染
};
影响
  • 代码行数:从156行减少至约25行
  • 技术栈原生:使用已有的Zustand依赖
  • 可测试性:Zustand store易于测试
  • 工作量:约1.5小时

Summary

总结

  • Total suggestions: 4
  • High priority: 2 (Strategy, Observer)
  • Medium priority: 2 (Builder, Facade)
  • Estimated total effort: ~6 hours
  • Primary benefits: Reduced complexity, improved testability, stack-native idioms
undefined
  • 总建议数:4
  • 高优先级:2(策略、观察者)
  • 中优先级:2(建造者、外观)
  • 预估总工作量:约6小时
  • 主要收益:降低复杂度、提升可测试性、遵循技术栈原生语法
undefined

Evaluation Mode (JSON)

评估模式(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"
    }
  ]
}
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": "正确实现单例结构,包含私有构造函数和静态getInstance方法",
      "issues": ["未考虑线程安全(在JS单线程环境中不关键)"]
    },
    "testability": {
      "score": 4,
      "rationale": "难以在测试中模拟或重置实例",
      "issues": [
        "缺少用于测试隔离的重置方法",
        "静态实例导致无法进行依赖注入",
        "测试必须按特定顺序执行或共享状态"
      ],
      "suggestions": [
        "添加测试友好的重置方法resetInstance()(需添加适当保护)",
        "考虑改用依赖注入"
      ]
    },
    "single_responsibility": {
      "score": 9,
      "rationale": "仅专注于配置管理",
      "issues": []
    },
    "open_closed": {
      "score": 7,
      "rationale": "配置可扩展,但添加新配置源需要修改现有代码",
      "suggestions": ["考虑使用策略模式处理配置源"]
    },
    "documentation": {
      "score": 6,
      "rationale": "包含JSDoc,但缺少选择单例的理由说明",
      "suggestions": ["在JSDoc中说明选择单例而非依赖注入的原因", "添加使用示例"]
    }
  },
  "recommendations": [
    {
      "priority": "high",
      "suggestion": "添加测试友好的重置机制或重构为依赖注入",
      "rationale": "当前实现导致测试困难"
    },
    {
      "priority": "medium",
      "suggestion": "在JSDoc中添加单例使用理由",
      "rationale": "团队成员需理解此处使用全局状态的必要性"
    }
  ]
}

Constraints & Guidelines

约束与指南

Read-Only Analysis

只读分析

  • No modifications: This skill only analyzes and suggests, never modifies code
  • No file creation: Does not generate refactored code files
  • User decision: All suggestions require explicit user approval before implementation
  • 不修改代码:本Skill仅进行分析和建议,绝不修改代码
  • 不创建文件:不会生成重构后的代码文件
  • 用户决策:所有建议需用户明确批准后方可实现

Language Focus

语言聚焦

  • Primary: TypeScript (
    .ts
    ,
    .tsx
    )
  • Secondary: JavaScript (
    .js
    ,
    .jsx
    )
  • Exclusions: Other languages (Python, Java, C#) not supported
  • 主要支持:TypeScript(
    .ts
    .tsx
  • 次要支持:JavaScript(
    .js
    .jsx
  • 不支持:其他语言(Python、Java、C#)

Pattern Coverage

模式覆盖

  • Creational (5): Singleton, Factory Method, Abstract Factory, Builder, Prototype
  • Structural (7): Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy
  • Behavioral (11): Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor, Interpreter
  • 创建型(5种):单例、工厂方法、抽象工厂、建造者、原型
  • 结构型(7种):适配器、桥接、组合、装饰器、外观、享元、代理
  • 行为型(11种):职责链、命令、迭代器、中介者、备忘录、观察者、状态、策略、模板方法、访问者、解释器

Performance Considerations

性能注意事项

  • Large codebases (>500 files): Use
    --scope
    to limit scan to specific directories
  • Parallel search: Grep searches run independently for each pattern
  • Caching: Stack detection results cached per session to avoid redundant package.json reads
  • 大型代码库(>500文件):使用
    --scope
    参数限制扫描目录
  • 并行搜索:每种模式的Grep搜索独立运行
  • 缓存:技术栈检测结果在会话内缓存,避免重复读取package.json

Usage Examples

使用示例

Basic Detection

基础检测

bash
undefined
bash
undefined

Detect all patterns in src/

检测src/目录下的所有模式

/design-patterns detect src/
/design-patterns detect src/

Detect only creational patterns

仅检测创建型模式

/design-patterns detect src/ --category=creational
/design-patterns detect src/ --category=creational

Focus on specific pattern

聚焦特定模式

/design-patterns detect src/ --pattern=singleton
undefined
/design-patterns detect src/ --pattern=singleton
undefined

Targeted Suggestions

定向建议

bash
undefined
bash
undefined

Get suggestions for payment module

获取支付模块的模式建议

/design-patterns suggest src/payment/
/design-patterns suggest src/payment/

Focus on specific smell

聚焦特定代码异味

/design-patterns suggest src/ --smell=switch-on-type
/design-patterns suggest src/ --smell=switch-on-type

High priority only

仅显示高优先级建议

/design-patterns suggest src/ --priority=high
undefined
/design-patterns suggest src/ --priority=high
undefined

Quality Evaluation

质量评估

bash
undefined
bash
undefined

Evaluate specific file

评估特定文件

/design-patterns evaluate src/services/api-client.ts
/design-patterns evaluate src/services/api-client.ts

Evaluate all singletons

评估所有单例模式实现

/design-patterns evaluate src/ --pattern=singleton
/design-patterns evaluate src/ --pattern=singleton

Full quality report

生成完整质量报告

/design-patterns evaluate src/ --detailed
undefined
/design-patterns evaluate src/ --detailed
undefined

Integration with Other Skills

与其他Skill的集成

This skill can be inherited by:
  • refactoring-specialist.md
    → Provides pattern knowledge for refactoring
  • code-reviewer.md
    → Adds pattern detection to review process
  • architecture-advisor.md
    → Informs architectural decisions with pattern usage
本Skill可被以下Skill继承:
  • refactoring-specialist.md
    → 为重构提供模式知识
  • code-reviewer.md
    → 在代码评审中添加模式检测功能
  • architecture-advisor.md
    → 为架构决策提供模式使用参考

Reference Files

参考文件

  • reference/patterns-index.yaml
    → Machine-readable index of 23 patterns with metadata
  • reference/creational.md
    → Creational patterns documentation
  • reference/structural.md
    → Structural patterns documentation
  • reference/behavioral.md
    → Behavioral patterns documentation
  • signatures/detection-rules.yaml
    → Regex patterns and heuristics for detection
  • signatures/code-smells.yaml
    → Mapping from code smells to applicable patterns
  • signatures/stack-patterns.yaml
    → Stack detection rules and native pattern equivalents
  • checklists/pattern-evaluation.md
    → Quality evaluation criteria and scoring guidelines
  • 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
    → 质量评估标准和评分指南

Version

版本信息

Skill Version: 1.0.0 Pattern Coverage: 23 GoF patterns Supported Stacks: 8 (React, Angular, NestJS, Vue, Express, RxJS, Redux/Zustand, ORMs) Last Updated: 2026-01-21
Skill版本:1.0.0 模式覆盖:23种GoF模式 支持的技术栈:8种(React、Angular、NestJS、Vue、Express、RxJS、Redux/Zustand、ORM) 最后更新:2026-01-21