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
| Input |
Output |
Duration |
| Code problem/smell |
Pattern recommendation + implementation guide |
2-5 min |
| Existing code |
Refactoring plan with pattern |
5-10 min |
| Pattern name |
Implementation example + guidance |
1-2 min |
Agent Behavior Contract
- Analyze first - Always examine existing code before recommending patterns
- Identify the problem - Clearly state the code smell or design issue
- Don't over-engineer - Apply patterns only when they solve real problems
- Explain trade-offs - Discuss pros and cons of each pattern
- Prefer simplicity - If a simpler solution exists, recommend it
- Show examples - Provide TypeScript code examples
- Consider alternatives - Mention related or alternative patterns
Pattern Selection Decision Tree
Object Creation Problems?
├─ 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?
├─ 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?
├─ 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.
- Read the code - Understand current implementation
- 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.
- Use decision tree - Navigate the decision tree above
- 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
- Consider alternatives - Evaluate 2-3 patterns if multiple fit
- 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.
- Show structure - Explain key participants (interfaces, classes, relationships)
- Provide example - Write TypeScript code demonstrating the pattern
- Explain flow - Walk through how components interact
- Point out gotchas - Warn about common mistakes
Verification: Implementation follows pattern principles and solves the original problem.
Common Scenarios → Patterns
| Scenario |
Pattern |
Why |
| Multiple button types trigger save, but implementation differs |
Strategy |
Swap save algorithms at runtime |
| UI needs to update when data changes |
Observer |
Automatic notification system |
| Need to add logging, validation to existing objects |
Decorator |
Add behavior without modifying originals |
| Working with legacy API that doesn't match your interface |
Adapter |
Bridge incompatible interfaces |
| Complex library with 50 classes, just need simple operations |
Facade |
Simplified interface to subsystem |
| Creating game characters with many customization options |
Builder |
Step-by-step construction |
| Document editor with undo/redo |
Command |
Encapsulate operations as objects |
| Connection states: disconnected, connecting, connected |
State |
Behavior changes with state |
| Need to save object snapshots for rollback |
Memento |
Capture and restore state without breaking encapsulation |
Anti-Patterns
| Avoid |
Why |
Instead |
| Pattern for pattern's sake |
Adds unnecessary complexity |
Identify actual problem first |
| Singleton everywhere |
Hidden dependencies, hard to test |
Dependency injection |
| Deep decorator chains |
Debugging nightmare |
Consider composition or other patterns |
| Premature abstraction |
YAGNI violation |
Wait for clear pattern of repetition |
| Factory for single product |
Over-engineering |
Direct instantiation is fine |
| Observer for everything |
Memory leaks, performance issues |
Use only when truly needed |
Verification
After applying a pattern:
Extension Points
- Custom patterns: Document your own domain-specific patterns based on these fundamentals
- Pattern combinations: Some problems benefit from combining multiple patterns
- Refactoring catalog: Build a library of before/after refactorings for your codebase
References
- Creational Patterns - Factory Method, Abstract Factory, Builder, Singleton
- Structural Patterns - Adapter, Decorator, Facade
- Behavioral Patterns - Observer, Strategy, Command, State, Template Method, Memento
- Refactoring.Guru - Complete catalog with examples
Note: Pattern selection requires judgment. When in doubt, prefer simpler solutions over pattern application.
1---2name: design-patterns-73description: 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.4license: MIT5---6
7# Design Patterns
8
9Expert 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.
10
11## Triggers
12
13- `which pattern should I use` - Pattern selection guidance
14- `refactor this code` - Identify and apply patterns to improve existing code
15- `how to decouple` - Find patterns to reduce coupling
16- `design pattern for` - Specific pattern recommendations
17- `code smells` - Identify problems that patterns can solve
18
19## Quick Reference
20
21| Input | Output | Duration |
22|-------|--------|----------|
23| Code problem/smell | Pattern recommendation + implementation guide | 2-5 min |
24| Existing code | Refactoring plan with pattern | 5-10 min |
25| Pattern name | Implementation example + guidance | 1-2 min |
26
27## Agent Behavior Contract
28
291. **Analyze first** - Always examine existing code before recommending patterns
302. **Identify the problem** - Clearly state the code smell or design issue
313. **Don't over-engineer** - Apply patterns only when they solve real problems
324. **Explain trade-offs** - Discuss pros and cons of each pattern
335. **Prefer simplicity** - If a simpler solution exists, recommend it
346. **Show examples** - Provide TypeScript code examples
357. **Consider alternatives** - Mention related or alternative patterns
36
37## Pattern Selection Decision Tree
38
39### Object Creation Problems?
40
41```
42├─ Need to create objects without specifying concrete classes?
43│ └─→ Factory Method
44│
45├─ Need families of related objects to work together?
46│ └─→ Abstract Factory
47│
48├─ Complex object with many optional parameters?
49│ └─→ Builder
50│
51└─ Need exactly one instance with global access?
52 └─→ Singleton (⚠️ use sparingly)
53```
54
55### Behavior/Algorithm Problems?
56
57```
58├─ Need to swap algorithms at runtime?
59│ └─→ Strategy
60│
61├─ Behavior changes based on internal state?
62│ └─→ State
63│
64├─ Need to notify multiple objects of changes?
65│ └─→ Observer
66│
67├─ Want to queue, log, or undo operations?
68│ └─→ Command
69│
70├─ Need to save/restore object state (undo/redo, snapshots)?
71│ └─→ Memento
72│
73└─ Define algorithm skeleton, let subclasses override steps?
74 └─→ Template Method
75```
76
77### Structure/Interface Problems?
78
79```
80├─ Incompatible interfaces need to work together?
81│ └─→ Adapter
82│
83├─ Need to add responsibilities without subclassing?
84│ └─→ Decorator
85│
86└─ Want to simplify complex subsystem?
87 └─→ Facade
88```
89
90## Process
91
92### Phase 1: Identify the Problem
93
94Analyze the code to identify specific issues.
95
961. **Read the code** - Understand current implementation
972. **Identify code smells** - Look for:
98 - Tight coupling between classes
99 - Large constructors or parameter lists
100 - Conditional logic that changes frequently
101 - Duplicate code across similar classes
102 - Global state or singletons everywhere
103 - Classes with too many responsibilities
104
105**Verification:** You can clearly articulate the specific problem or limitation.
106
107### Phase 2: Match Problem to Pattern
108
109Select the most appropriate pattern.
110
1111. **Use decision tree** - Navigate the decision tree above
1122. **Consult reference files** - Read detailed pattern documentation:
113 - `references/creational.md` - Factory Method, Abstract Factory, Builder, Singleton
114 - `references/structural.md` - Adapter, Decorator, Facade
115 - `references/behavioral.md` - Observer, Strategy, Command, State, Template Method
1163. **Consider alternatives** - Evaluate 2-3 patterns if multiple fit
1174. **Explain trade-offs** - Discuss pros/cons of recommended approach
118
119**Verification:** The pattern directly addresses the identified problem.
120
121### Phase 3: Implement Solution
122
123Guide implementation with concrete examples.
124
1251. **Show structure** - Explain key participants (interfaces, classes, relationships)
1262. **Provide example** - Write TypeScript code demonstrating the pattern
1273. **Explain flow** - Walk through how components interact
1284. **Point out gotchas** - Warn about common mistakes
129
130**Verification:** Implementation follows pattern principles and solves the original problem.
131
132## Common Scenarios → Patterns
133
134| Scenario | Pattern | Why |
135|----------|---------|-----|
136| Multiple button types trigger save, but implementation differs | Strategy | Swap save algorithms at runtime |
137| UI needs to update when data changes | Observer | Automatic notification system |
138| Need to add logging, validation to existing objects | Decorator | Add behavior without modifying originals |
139| Working with legacy API that doesn't match your interface | Adapter | Bridge incompatible interfaces |
140| Complex library with 50 classes, just need simple operations | Facade | Simplified interface to subsystem |
141| Creating game characters with many customization options | Builder | Step-by-step construction |
142| Document editor with undo/redo | Command | Encapsulate operations as objects |
143| Connection states: disconnected, connecting, connected | State | Behavior changes with state |
144| Need to save object snapshots for rollback | Memento | Capture and restore state without breaking encapsulation |
145
146## Anti-Patterns
147
148| Avoid | Why | Instead |
149|-------|-----|---------|
150| Pattern for pattern's sake | Adds unnecessary complexity | Identify actual problem first |
151| Singleton everywhere | Hidden dependencies, hard to test | Dependency injection |
152| Deep decorator chains | Debugging nightmare | Consider composition or other patterns |
153| Premature abstraction | YAGNI violation | Wait for clear pattern of repetition |
154| Factory for single product | Over-engineering | Direct instantiation is fine |
155| Observer for everything | Memory leaks, performance issues | Use only when truly needed |
156
157## Verification
158
159After applying a pattern:
160
161- [ ] The original problem is solved
162- [ ] Code is more maintainable, not more complex
163- [ ] Pattern participants have clear responsibilities
164- [ ] Tests pass and cover new structure
165- [ ] Team members understand the pattern choice
166- [ ] No unnecessary abstraction layers added
167
168## Extension Points
169
1701. **Custom patterns**: Document your own domain-specific patterns based on these fundamentals
1712. **Pattern combinations**: Some problems benefit from combining multiple patterns
1723. **Refactoring catalog**: Build a library of before/after refactorings for your codebase
173
174## References
175
176- [Creational Patterns](references/creational.md) - Factory Method, Abstract Factory, Builder, Singleton
177- [Structural Patterns](references/structural.md) - Adapter, Decorator, Facade
178- [Behavioral Patterns](references/behavioral.md) - Observer, Strategy, Command, State, Template Method, Memento
179- [Refactoring.Guru](https://refactoring.guru/design-patterns/catalog) - Complete catalog with examples
180
181---
182
183**Note**: Pattern selection requires judgment. When in doubt, prefer simpler solutions over pattern application.