AgentSkillsCN

design-patterns

指导何时以及如何应用设计模式。当您遇到以下情况时可使用此技能:(1) 询问应选用何种模式;(2) 对代码进行重构;(3) 讨论代码异味;(4) 需要解耦组件;(5) 构建可扩展系统。

SKILL.md
--- frontmatter
name: design-patterns
version: 1.0.0
description: "Guidance on when and how to apply design patterns. Use when: (1) asking which pattern to use, (2) refactoring code, (3) discussing code smells, (4) need to decouple components, (5) building extensible systems."
license: MIT
model: claude-opus-4-5-20251101
metadata:
  domains: [design-patterns, architecture, refactoring, oop]
  source: https://refactoring.guru/design-patterns/catalog
  language: typescript

Design Patterns

Expert guidance on applying Gang of Four design patterns to solve common software design problems. This skill helps you identify code smells, match them to appropriate patterns, and implement solutions effectively.

Triggers

  • which pattern should I use - Pattern selection guidance
  • refactor this code - Identify and apply patterns to improve existing code
  • how to decouple - Find patterns to reduce coupling
  • design pattern for - Specific pattern recommendations
  • code smells - Identify problems that patterns can solve

Quick Reference

InputOutputDuration
Code problem/smellPattern recommendation + implementation guide2-5 min
Existing codeRefactoring plan with pattern5-10 min
Pattern nameImplementation example + guidance1-2 min

Agent Behavior Contract

  1. Analyze first - Always examine existing code before recommending patterns
  2. Identify the problem - Clearly state the code smell or design issue
  3. Don't over-engineer - Apply patterns only when they solve real problems
  4. Explain trade-offs - Discuss pros and cons of each pattern
  5. Prefer simplicity - If a simpler solution exists, recommend it
  6. Show examples - Provide TypeScript code examples
  7. Consider alternatives - Mention related or alternative patterns

Pattern Selection Decision Tree

Object Creation Problems?

code
├─ Need to create objects without specifying concrete classes?
│  └─→ Factory Method
│
├─ Need families of related objects to work together?
│  └─→ Abstract Factory
│
├─ Complex object with many optional parameters?
│  └─→ Builder
│
└─ Need exactly one instance with global access?
   └─→ Singleton (⚠️ use sparingly)

Behavior/Algorithm Problems?

code
├─ Need to swap algorithms at runtime?
│  └─→ Strategy
│
├─ Behavior changes based on internal state?
│  └─→ State
│
├─ Need to notify multiple objects of changes?
│  └─→ Observer
│
├─ Want to queue, log, or undo operations?
│  └─→ Command
│
├─ Need to save/restore object state (undo/redo, snapshots)?
│  └─→ Memento
│
└─ Define algorithm skeleton, let subclasses override steps?
   └─→ Template Method

Structure/Interface Problems?

code
├─ Incompatible interfaces need to work together?
│  └─→ Adapter
│
├─ Need to add responsibilities without subclassing?
│  └─→ Decorator
│
└─ Want to simplify complex subsystem?
   └─→ Facade

Process

Phase 1: Identify the Problem

Analyze the code to identify specific issues.

  1. Read the code - Understand current implementation
  2. Identify code smells - Look for:
    • Tight coupling between classes
    • Large constructors or parameter lists
    • Conditional logic that changes frequently
    • Duplicate code across similar classes
    • Global state or singletons everywhere
    • Classes with too many responsibilities

Verification: You can clearly articulate the specific problem or limitation.

Phase 2: Match Problem to Pattern

Select the most appropriate pattern.

  1. Use decision tree - Navigate the decision tree above
  2. Consult reference files - Read detailed pattern documentation:
    • references/creational.md - Factory Method, Abstract Factory, Builder, Singleton
    • references/structural.md - Adapter, Decorator, Facade
    • references/behavioral.md - Observer, Strategy, Command, State, Template Method
  3. Consider alternatives - Evaluate 2-3 patterns if multiple fit
  4. Explain trade-offs - Discuss pros/cons of recommended approach

Verification: The pattern directly addresses the identified problem.

Phase 3: Implement Solution

Guide implementation with concrete examples.

  1. Show structure - Explain key participants (interfaces, classes, relationships)
  2. Provide example - Write TypeScript code demonstrating the pattern
  3. Explain flow - Walk through how components interact
  4. Point out gotchas - Warn about common mistakes

Verification: Implementation follows pattern principles and solves the original problem.

Common Scenarios → Patterns

ScenarioPatternWhy
Multiple button types trigger save, but implementation differsStrategySwap save algorithms at runtime
UI needs to update when data changesObserverAutomatic notification system
Need to add logging, validation to existing objectsDecoratorAdd behavior without modifying originals
Working with legacy API that doesn't match your interfaceAdapterBridge incompatible interfaces
Complex library with 50 classes, just need simple operationsFacadeSimplified interface to subsystem
Creating game characters with many customization optionsBuilderStep-by-step construction
Document editor with undo/redoCommandEncapsulate operations as objects
Connection states: disconnected, connecting, connectedStateBehavior changes with state
Need to save object snapshots for rollbackMementoCapture and restore state without breaking encapsulation

Anti-Patterns

AvoidWhyInstead
Pattern for pattern's sakeAdds unnecessary complexityIdentify actual problem first
Singleton everywhereHidden dependencies, hard to testDependency injection
Deep decorator chainsDebugging nightmareConsider composition or other patterns
Premature abstractionYAGNI violationWait for clear pattern of repetition
Factory for single productOver-engineeringDirect instantiation is fine
Observer for everythingMemory leaks, performance issuesUse only when truly needed

Verification

After applying a pattern:

  • The original problem is solved
  • Code is more maintainable, not more complex
  • Pattern participants have clear responsibilities
  • Tests pass and cover new structure
  • Team members understand the pattern choice
  • No unnecessary abstraction layers added

Extension Points

  1. Custom patterns: Document your own domain-specific patterns based on these fundamentals
  2. Pattern combinations: Some problems benefit from combining multiple patterns
  3. Refactoring catalog: Build a library of before/after refactorings for your codebase

References


Note: Pattern selection requires judgment. When in doubt, prefer simpler solutions over pattern application.