design-patterns
Use when designing software architecture, refactoring code structure, solving recurring design problems, or when code exhibits symptoms like tight coupling, rigid hierarchies, scattered responsibilities, or difficult-to-test components. Also use when choosing between architectural approaches or reviewing code for structural improvements.
What this skill does
# Design Patterns ## Overview Design patterns are proven solutions to recurring software design problems. They provide a shared vocabulary for discussing design and capture collective wisdom refined through decades of real-world use. **Core Philosophy:** Patterns are templates you adapt to your context, not blueprints to copy. Use the right pattern when it genuinely simplifies your design—not to impress or over-engineer. ## Foundational Principles These principles underpin all good design: | Principle | Meaning | Violation Symptom | |-----------|---------|-------------------| | **Encapsulate What Varies** | Isolate changing parts from stable parts | Changes ripple through codebase | | **Program to Interfaces** | Depend on abstractions, not concretions | Can't swap implementations | | **Composition Over Inheritance** | Build behavior by composing objects | Deep rigid class hierarchies | | **Loose Coupling** | Minimize interdependency between objects | Can't change one thing without breaking another | | **Open-Closed** | Open for extension, closed for modification | Must edit existing code for new features | | **Single Responsibility** | One reason to change per class | Classes doing too many things | | **Dependency Inversion** | High-level modules don't depend on low-level | Business logic coupled to infrastructure | ## Pattern Selection Guide ### By Problem Type ``` CREATING OBJECTS ├── Complex/conditional creation ──────────→ Factory Method ├── Families of related objects ───────────→ Abstract Factory ├── Step-by-step construction ─────────────→ Builder ├── Clone existing objects ────────────────→ Prototype └── Single instance needed ────────────────→ Singleton (use sparingly!) STRUCTURING/COMPOSING OBJECTS ├── Incompatible interface ────────────────→ Adapter ├── Simplify complex subsystem ────────────→ Facade ├── Tree/hierarchy structure ──────────────→ Composite ├── Add behavior dynamically ──────────────→ Decorator └── Control access to object ──────────────→ Proxy MANAGING COMMUNICATION/BEHAVIOR ├── One-to-many notification ──────────────→ Observer ├── Encapsulate requests as objects ───────→ Command ├── Behavior varies by internal state ─────→ State ├── Swap algorithms at runtime ────────────→ Strategy ├── Algorithm skeleton with hooks ─────────→ Template Method ├── Reduce N-to-N communication ───────────→ Mediator └── Sequential handlers ───────────────────→ Chain of Responsibility MANAGING DATA ACCESS ├── Abstract data source ──────────────────→ Repository ├── Track changes for atomic commit ───────→ Unit of Work ├── Ensure object identity ────────────────→ Identity Map ├── Defer expensive loading ───────────────→ Lazy Load ├── Map objects to database ───────────────→ Data Mapper └── Shape data for transfer ───────────────→ DTO ``` ### By Symptom | Symptom | Consider | |---------|----------| | Giant switch/if-else on type | Strategy, State, or polymorphism | | Duplicate code across classes | Template Method, Strategy | | Need to notify many objects of changes | Observer | | Complex object creation logic | Factory, Builder | | Adding features bloats class | Decorator | | Third-party API doesn't fit your code | Adapter | | Too many dependencies between components | Mediator, Facade | | Can't test without database/network | Repository, Dependency Injection | | Need undo/redo | Command | | Object behavior depends on state | State | | Request needs processing by multiple handlers | Chain of Responsibility | ### Domain Logic: Transaction Script vs Domain Model | Factor | Transaction Script | Domain Model | |--------|-------------------|--------------| | Logic complexity | Simple (< 500 lines) | Complex, many rules | | Business rules | Few, straightforward | Many, interacting | | Operations | CRUD-heavy | Rich behavior | | Team/timeline | Small team, quick delivery | Long-term maintenance | | Testing | Integration tests | Unit tests on domain | **Rule of thumb:** Start with Transaction Script. Refactor to Domain Model when procedural code becomes hard to maintain. ## Quick Reference ### Tier 1: Essential Patterns (Master First) | Pattern | One-Line | When to Use | Reference | |---------|----------|-------------|-----------| | **Strategy** | Encapsulate interchangeable algorithms | Multiple ways to do something, swap at runtime | [strategy.md](patterns/strategy.md) | | **Observer** | Notify dependents of state changes | Event systems, reactive updates | [observer.md](patterns/observer.md) | | **Factory** | Encapsulate object creation | Complex/conditional instantiation | [factory.md](patterns/factory.md) | | **Decorator** | Add behavior dynamically | Extend without inheritance | [decorator.md](patterns/decorator.md) | | **Command** | Encapsulate requests as objects | Undo/redo, queuing, logging | [command.md](patterns/command.md) | ### Tier 2: Structural Patterns | Pattern | One-Line | When to Use | Reference | |---------|----------|-------------|-----------| | **Adapter** | Convert interfaces | Integrate incompatible code | [adapter.md](patterns/adapter.md) | | **Facade** | Simplify complex subsystems | Hide complexity behind simple API | [facade.md](patterns/facade.md) | | **Composite** | Uniform tree structures | Part-whole hierarchies | [composite.md](patterns/composite.md) | | **Proxy** | Control access to objects | Lazy load, access control, caching | [proxy.md](patterns/proxy.md) | ### Tier 3: Enterprise/Architectural Patterns | Pattern | One-Line | When to Use | Reference | |---------|----------|-------------|-----------| | **Repository** | Collection-like data access | Decouple domain from data layer | [repository.md](patterns/repository.md) | | **Unit of Work** | Coordinate atomic changes | Transaction management | [unit-of-work.md](patterns/unit-of-work.md) | | **Service Layer** | Orchestrate business operations | Define application boundary | [service-layer.md](patterns/service-layer.md) | | **DTO** | Shape data for transfer | API contracts, prevent over-exposure | [dto.md](patterns/dto.md) | ### Additional Important Patterns | Pattern | One-Line | When to Use | Reference | |---------|----------|-------------|-----------| | **Builder** | Step-by-step object construction | Complex objects, fluent APIs | [builder.md](patterns/builder.md) | | **State** | Behavior changes with state | State machines, workflow | [state.md](patterns/state.md) | | **Template Method** | Algorithm skeleton with hooks | Framework extension points | [template-method.md](patterns/template-method.md) | | **Chain of Responsibility** | Pass request along handlers | Middleware, pipelines | [chain-of-responsibility.md](patterns/chain-of-responsibility.md) | | **Mediator** | Centralize complex communication | Reduce component coupling | [mediator.md](patterns/mediator.md) | | **Lazy Load** | Defer expensive loading | Performance, large object graphs | [lazy-load.md](patterns/lazy-load.md) | | **Identity Map** | Ensure object identity | ORM, prevent duplicates | [identity-map.md](patterns/identity-map.md) | ## Common Mistakes | Mistake | Symptom | Fix | |---------|---------|-----| | **Pattern Overuse** | Simple operations require navigating many classes | Only use when solving real problem | | **Wrong Pattern** | Code feels forced, awkward | Re-examine actual problem | | **Inheritance Abuse** | Deep hierarchies, fragile base class | Favor composition (Strategy, Decorator) | | **Singleton Abuse** | Global state, hidden dependencies, hard to test | Use dependency injection instead | | **Premature Abstraction** | Interfaces with single implementation | Wait for real need to vary | ## Anti-Patterns to Recognize - **God Object:** One class does everything → Split using SRP - **Anemic Domain Model:** Objects are just data bags → Move behavior to objects - **Golden Hammer:** Same pattern everywhere → Match pattern to problem - **Lava Flow:** Dead code nobody removes → Delete it, VCS has your back ## Modern Variations | Modern Pattern | Based On |
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.