mcpField
D
design-patterns

design-patterns

github.com/florianbruniaux開発6.3k65 回インストール2 日前に更新
リポジトリ

design-patterns について

TypeScript と JavaScript のコードベースを分析する読み取り専用スキルです。GoF パターンの検出、スタックに応じた提案、実装品質の評価を行います。

主な機能

  1. 0123 種類の GoF パターンを検出
  2. 02フレームワークとライブラリを識別
  3. 03スタックに応じたパターンを提案
  4. 04実装品質をスコア評価
  5. 05JSON と Markdown のレポートを生成
  6. 06ファイルを変更せずに分析

活用シーン

  1. 01TypeScript プロジェクトのパターンを一覧化
  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 のコードベースで Gang of Four(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:deps に react があり、*.jsx/*.tsx ファイルがある
  • Angular:@angular/core と angular.json がある
  • NestJS:@nestjs/core と nest-cli.json がある
  • Vue:Vue v3 以降と *.vue ファイルがある
  • Express:deps に express があり、app.use パターンがある
  • RxJS:deps に rxjs があり、Observable が使用されている
  • Redux/Zustand:deps に redux/zustand があり、ストアのパターンがある
  • Prisma/TypeORM:deps に prisma/typeorm があり、スキーマファイルがある

出力:

{
  "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. 型による切り替え -> Strategy/Factory パターン
  2. 長いパラメーターリスト(4 個超) -> Builder パターン
  3. グローバル状態へのアクセス -> Singleton(または、できれば DI)
  4. 状態に関する条件分岐の重複 -> State パターン
  5. 通知ロジックの分散 -> Observer パターン
  6. 複雑なオブジェクト生成 -> Factory/Abstract Factory
  7. 具象クラスへの密結合 -> Adapter/Bridge
  8. インターフェース変換の繰り返し -> Adapter パターン
  9. 機能追加時の深いネスト -> Decorator パターン
  10. 責務が多すぎる大規模クラス -> Facade パターン

検出ヒューリスティクス:

  • switch (.*type)、switch (.*kind)、switch (.*mode) を Grep で検索します
  • 関数のパラメーター数を数えます: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

適応例:

パターンスタックネイティブな代替手段推奨事項
SingletonReactContext API + ProvidergetInstance() の代わりに createContext() を使用します
ObserverAngularRxJS Subject/BehaviorSubjectカスタム実装ではなく、組み込みの Observables を使用します
DecoratorNestJS@Injectable() デコレーター + Interceptorsフレームワークのインターセプターを使用します
StrategyVue 3Composition API の composablesクラスの代わりに ref() + composables を使用します
Chain of ResponsibilityExpressMiddleware(app.use())Express のミドルウェアチェーンを使用します
CommandReduxAction creators + reducersカスタムのコマンドオブジェクトではなく、Redux のアクションを使用します
フェーズ 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 を使う Singleton)
  • 神クラス(責務が多すぎる)
  • 漏れのある抽象化(内部構造を公開している)
  • エラーハンドリングの欠如
  • 不適切な命名(内容を表す名前ではなく、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 に適応した 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);
  // ...
};

影響:

  • 複雑さ:循環的複雑度を 12 から 2 に削減します
  • 拡張性:新しい決済方法を追加する場合は新しいフックを作成するだけで、既存のコードを変更する必要はありません
  • テスト容易性:各 Strategy フックを個別にテストできます
  • 作業量:約 2 時間(ロジックをフックに切り出し、テストを追加)

中優先度

2. Observer パターン:src/cart/CartManager.ts:23-156

コードスメル:手動の通知ロジックが 8 つのメソッドに分散しています

現状:更新関数を呼び出す手動のループ 推奨:Zustand ストアを使用します(すでに依存関係に含まれています)

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

影響:

  • LOC:156 行から約 25 行に削減します
  • スタックに適合:既存の Zustand 依存関係を使用します
  • テスト容易性:Zustand ストアは簡単にテストできます
  • 作業量:約 1.5 時間

概要

  • 提案の合計:4
  • 優先度:高:2(Strategy、Observer)
  • 優先度:中:2(Builder、Facade)
  • 推定合計工数:約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 パターンの対象範囲:GoFパターン23種 サポート対象のスタック:8(React、Angular、NestJS、Vue、Express、RxJS、Redux/Zustand、ORM) 最終更新日:2026-01-21

コメント