Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

design-patterns设计模式

Agent Skill

用于辅助界面设计、视觉规范、排版、配色、布局和交互体验优化。它适合让 Agent 根据产品场景整理页面结构、生成 UI 方案、检查视觉一致性或改进组件层级。使用时需要结合现有品牌、设计系统和用户任务,不应只堆装饰元素;涉及真实页面改动时,应通过截图或浏览器预览检查文本溢出、对齐和响应式表现。

总安装

1,364

周安装

58

GitHub Stars

3,971

下载量

478
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:design-patterns(设计模式)
来源仓库:https://github.com/florianbruniaux/claude-code-ultimate-guide
仓库路径:skills/design-patterns
安装命令:
npx skills add https://github.com/florianbruniaux/claude-code-ultimate-guide --skill design-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

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

简介

design-patterns 提供设计模式评估与重构建议,适合辅助代码结构优化。

  • 适用于分析单例、策略等模式的实现质量,并生成改进方案。
  • 通过 github 安装后,结合项目文件进行模式识别和评分反馈。
  • 使用时需注意测试隔离、依赖注入等可维护性问题,避免过度标记语言习语差异。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Design Patterns Analyzer Skill

Purpose: Detect, suggest, and evaluate Gang of Four (GoF) design patterns in TypeScript/JavaScript codebases with stack-aware adaptations.

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

Operating Modes

Mode 1: Detection

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

Mode 2: Suggestion

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

Mode 3: Evaluation

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

Methodology

Phase 1: Stack Detection

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:

{
  "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

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.

  1. 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

  1. 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.)

Phase 3: Code Smell Detection

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\(

Phase 4: Stack-Aware Suggestions

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

Phase 5: Quality Evaluation

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)

Output Formats

Detection Mode (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"
  ]
}

Suggestion Mode (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):

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)**:

// 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)

---

## Medium Priority

### 2. Observer Pattern → `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)

// 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

---

## 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

Evaluation Mode (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"
    }
  ]
}

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

Language Focus

  • Primary: TypeScript (.ts, .tsx)
  • Secondary: JavaScript (.js, .jsx)
  • Exclusions: Other languages (Python, Java, C#) not supported

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

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

Usage Examples

Basic Detection

# 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

Targeted Suggestions

# 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

Quality Evaluation

# 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

Integration with Other Skills

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

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

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

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.04%
按下载量换算163

Claude

31.37%
按下载量换算150

Cursor

17.77%
按下载量换算85

Gemini CLI

9.06%
按下载量换算43

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills