design-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDesign 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
核心功能
- Stack Detection: Identify primary framework/library (React, Angular, NestJS, Vue, Express, RxJS, Redux, ORMs)
- Pattern Detection: Find existing implementations of 23 GoF patterns
- Smart Suggestions: Recommend patterns to fix code smells, using stack-native idioms when available
- Quality Evaluation: Assess pattern implementation quality against best practices
- 技术栈检测:识别主要框架/库(React、Angular、NestJS、Vue、Express、RxJS、Redux、ORM)
- 模式检测:查找23种GoF模式的现有实现
- 智能建议:推荐可修复代码异味的模式,优先使用技术栈原生语法
- 质量评估:对照最佳实践评估模式实现的质量
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 GenerationExample 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=jsonMode 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 ExamplesExample 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=creationalMode 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 RecommendationsExample 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=observerMethodology
方法论
Phase 1: Stack Detection
阶段1:技术栈检测
Sources (in priority order):
- → Check dependencies and devDependencies
package.json - Framework-specific files → ,
angular.json,next.config.*,nest-cli.jsonvite.config.* - → Check compilerOptions, paths, lib
tsconfig.json - File extensions → ,
*.jsx,*.tsxpresence*.vue
Detection Rules (from ):
signatures/stack-patterns.yaml- React: in deps +
reactfiles*.jsx/*.tsx - Angular: +
@angular/coreangular.json - NestJS: +
@nestjs/corenest-cli.json - Vue: v3+ +
vuefiles*.vue - Express: in deps +
expresspatternsapp.use - RxJS: in deps + Observable usage
rxjs - Redux/Zustand: /
reduxin deps + store patternszustand - Prisma/TypeORM: /
prismain deps + schema filestypeorm
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
}
}数据源(优先级排序):
- → 检查依赖项和开发依赖项
package.json - 框架特定文件 → 、
angular.json、next.config.*、nest-cli.jsonvite.config.* - → 检查compilerOptions、paths、lib配置
tsconfig.json - 文件扩展名 → 是否存在、
*.jsx、*.tsx文件*.vue
检测规则(来自):
signatures/stack-patterns.yaml- React:依赖中包含+ 存在
react文件*.jsx/*.tsx - Angular:依赖中包含+ 存在
@angular/coreangular.json - NestJS:依赖中包含+ 存在
@nestjs/corenest-cli.json - Vue:依赖中包含v3+版本的+ 存在
vue文件*.vue - Express:依赖中包含+ 存在
express模式app.use - RxJS:依赖中包含+ 存在Observable用法
rxjs - Redux/Zustand:依赖中包含/
redux+ 存在store模式zustand - Prisma/TypeORM:依赖中包含/
prisma+ 存在schema文件typeorm
输出示例:
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:
-
Glob Phase: Find candidate files by naming convention
- ,
*Singleton*.ts,*Factory*.ts,*Strategy*.ts, etc.*Observer*.ts - ,
*Manager*.ts,*Builder*.ts,*Adapter*.ts, etc.*Proxy*.ts
-
Grep Phase: Search for pattern signatures (from)
signatures/detection-rules.yaml- Primary signals: ,
private constructor,static getInstance(),subscribe(), etc.createXxx() - Secondary signals: Interface naming, delegation patterns, method signatures
- Primary signals:
-
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:
- : Pattern implemented using stack-native features (React Context, Angular Services, NestJS Guards, etc.)
native - : Manual TypeScript implementation
custom - : Third-party library providing pattern (RxJS Subject, Redux Store, etc.)
library
搜索策略:
-
全局匹配阶段:通过命名规则查找候选文件
- 、
*Singleton*.ts、*Factory*.ts、*Strategy*.ts等*Observer*.ts - 、
*Manager*.ts、*Builder*.ts、*Adapter*.ts等*Proxy*.ts
-
特征匹配阶段:搜索模式特征签名(来自)
signatures/detection-rules.yaml- 主要信号:、
private constructor、static getInstance()、subscribe()等createXxx() - 次要信号:接口命名、委托模式、方法签名
- 主要信号:
-
验证阶段:验证模式结构
- 解析类/接口定义
- 验证关系(继承、组合、委托)
- 检查是完整模式实现还是部分使用
置信度评分规则:
- 0.9-1.0:存在所有主要+次要信号,结构完全匹配
- 0.7-0.89:存在所有主要信号+部分次要信号,有轻微偏差
- 0.5-0.69:存在主要信号,缺少次要验证
- 0.3-0.49:命名规则匹配,结构证据薄弱
- 0.0-0.29:证据不足,可能为误报
分类:
- :使用技术栈原生功能实现的模式(React Context、Angular Services、NestJS Guards等)
native - :手动TypeScript实现
custom - :第三方库提供的模式(RxJS Subject、Redux Store等)
library
Phase 3: Code Smell Detection
阶段3:代码异味检测
Target Smells (from ):
signatures/code-smells.yaml- Switch on Type → Strategy/Factory pattern
- Long Parameter List (>4) → Builder pattern
- Global State Access → Singleton (or preferably DI)
- Duplicated Conditionals on State → State pattern
- Scattered Notification Logic → Observer pattern
- Complex Object Creation → Factory/Abstract Factory
- Tight Coupling to Concrete Classes → Adapter/Bridge
- Repetitive Interface Conversions → Adapter pattern
- Deep Nesting for Feature Addition → Decorator pattern
- Large Class with Many Responsibilities → Facade pattern
Detection Heuristics:
- Grep for ,
switch (.*type),switch (.*kind)switch (.*mode) - Count function parameters: (approximation for >4 params)
function \w+\([^)]{60,}\) - Search for global access: ,
window\.,global\.(not in config files)process\.env\.\w+ - Find state conditionals:
if.*state.*===.*&&.*if.*state.*=== - Find notification patterns: ,
forEach.*notifymap.*\.emit\(
目标异味(来自):
signatures/code-smells.yaml- 基于类型的Switch语句 → 策略/工厂模式
- 长参数列表(>4个) → 建造者模式
- 全局状态访问 → 单例(或优先使用依赖注入)
- 重复的状态条件判断 → 状态模式
- 分散的通知逻辑 → 观察者模式
- 复杂对象创建 → 工厂/抽象工厂模式
- 与具体类紧耦合 → 适配器/桥接模式
- 重复的接口转换 → 适配器模式
- 为添加功能而深度嵌套 → 装饰器模式
- 承担过多职责的大类 → 外观模式
检测启发式规则:
- 匹配、
switch (.*type)、switch (.*kind)switch (.*mode) - 统计函数参数:(近似判断参数>4个)
function \w+\([^)]{60,}\) - 搜索全局访问:、
window\.、global\.(配置文件除外)process\.env\.\w+ - 查找状态条件判断:
if.*state.*===.*&&.*if.*state.*=== - 查找通知模式:、
forEach.*notifymap.*\.emit\(
Phase 4: Stack-Aware Suggestions
阶段4:适配技术栈的建议
Adaptation Logic (from ):
signatures/stack-patterns.yamlIF 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-patternsExample Adaptations:
| Pattern | Stack | Native Alternative | Recommendation |
|---|---|---|---|
| Singleton | React | Context API + Provider | Use |
| Observer | Angular | RxJS Subject/BehaviorSubject | Use built-in Observables, not custom implementation |
| Decorator | NestJS | @Injectable() decorators + Interceptors | Use framework interceptors |
| Strategy | Vue 3 | Composition API composables | Use |
| Chain of Responsibility | Express | Middleware ( | Use Express middleware chain |
| Command | Redux | Action creators + reducers | Use Redux actions, not custom command objects |
适配逻辑(来自):
signatures/stack-patterns.yamlIF 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: 修复反模式的重构步骤适配示例:
| 模式 | 技术栈 | 原生替代方案 | 建议 |
|---|---|---|---|
| 单例 | React | Context API + Provider | 使用 |
| 观察者 | Angular | RxJS Subject/BehaviorSubject | 使用内置Observable,而非自定义实现 |
| 装饰器 | NestJS | @Injectable()装饰器 + Interceptors | 使用框架拦截器 |
| 策略 | Vue 3 | Composition API组合式函数 | 使用 |
| 职责链 | Express | 中间件( | 使用Express中间件链 |
| 命令 | Redux | Action创建器 + reducer | 使用Redux动作,而非自定义命令对象 |
Phase 5: Quality Evaluation
阶段5:质量评估
Criteria (from ):
checklists/pattern-evaluation.md- Correctness (0-10): Does it match the canonical pattern structure?
- Testability (0-10): Can dependencies be mocked/stubbed easily?
- Single Responsibility (0-10): Does it do one thing only?
- Open/Closed Principle (0-10): Extensible without modification?
- 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- 正确性(0-10):是否符合标准模式结构?
- 可测试性(0-10):是否易于模拟/存根依赖?
- 单一职责(0-10):是否仅承担一个职责?
- 开闭原则(0-10):是否可扩展而无需修改现有代码?
- 文档完整性(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
undefinedmarkdown
undefinedDesign Pattern Suggestions
设计模式建议
Scope:
Stack: React 18 + TypeScript + Stripe
Date: 2026-01-21
src/payment/范围:
技术栈:React 18 + TypeScript + Stripe
日期:2026-01-21
src/payment/High Priority
高优先级
1. Strategy Pattern → src/payment/processor.ts:45-89
src/payment/processor.ts:45-891. 策略模式 → src/payment/processor.ts:45-89
src/payment/processor.ts:45-89Code 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
src/cart/CartManager.ts:23-1562. 观察者模式 → src/cart/CartManager.ts:23-156
src/cart/CartManager.ts:23-156Code 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小时
- 主要收益:降低复杂度、提升可测试性、遵循技术栈原生语法
undefinedEvaluation 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 to limit scan to specific directories
--scope - 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
undefinedbash
undefinedDetect 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
undefinedTargeted Suggestions
定向建议
bash
undefinedbash
undefinedGet 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
undefinedQuality Evaluation
质量评估
bash
undefinedbash
undefinedEvaluate 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
undefinedIntegration with Other Skills
与其他Skill的集成
This skill can be inherited by:
- → Provides pattern knowledge for refactoring
refactoring-specialist.md - → Adds pattern detection to review process
code-reviewer.md - → Informs architectural decisions with pattern usage
architecture-advisor.md
本Skill可被以下Skill继承:
- → 为重构提供模式知识
refactoring-specialist.md - → 在代码评审中添加模式检测功能
code-reviewer.md - → 为架构决策提供模式使用参考
architecture-advisor.md
Reference Files
参考文件
- → Machine-readable index of 23 patterns with metadata
reference/patterns-index.yaml - → Creational patterns documentation
reference/creational.md - → Structural patterns documentation
reference/structural.md - → Behavioral patterns documentation
reference/behavioral.md - → Regex patterns and heuristics for detection
signatures/detection-rules.yaml - → Mapping from code smells to applicable patterns
signatures/code-smells.yaml - → Stack detection rules and native pattern equivalents
signatures/stack-patterns.yaml - → Quality evaluation criteria and scoring guidelines
checklists/pattern-evaluation.md
- → 包含23种模式元数据的机器可读索引
reference/patterns-index.yaml - → 创建型模式文档
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