MCPInstall

design-patterns

Agents should invoke this skill when choosing patterns, designing traits/interfaces/components, deciding abstraction boundaries, evaluating dependency injection/callbacks, or comparing implementation approaches in Rust, TypeScript/React, or Django/Python.

Installs
52
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/waybarrios/opencode-power-pack --skill design-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads design-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Design Patterns

Pattern recommendations tailored to common tech stacks. Every pattern recommendation includes when to use it, when to avoid it, and the trade-offs.

Quick Start

Choose a Pattern

  1. Identify the problem: What design challenge are you solving?
  2. Consider the context: What language? What scale? How often will this change?
  3. Evaluate options: 2-3 candidate patterns with trade-offs
  4. Recommend: The best fit for this specific context (not the "best pattern in general")

The golden rule: Patterns are tools, not goals. Use the simplest pattern that solves the problem. If no pattern fits, a plain function or struct is fine.


Rust Patterns

Newtype Pattern

Wrap a primitive to add type safety and domain meaning.

struct UserId(u64);
struct OrderId(u64);

// Now the compiler prevents mixing up UserId and OrderId
fn get_order(user: UserId, order: OrderId) -> Order { ... }

When to use: When two values have the same underlying type but different meanings. When to skip: One-off uses where a type alias suffices.

Builder Pattern

Construct complex objects step by step.

let config = ServerConfig::builder()
    .host("localhost")
    .port(8080)
    .max_connections(100)
    .build()?;

When to use: Structs with many optional fields, complex construction logic. When to skip: Structs with 1-3 required fields — just use new().

Typestate Pattern

Encode state transitions in the type system so invalid states are unrepresentable.

struct Connection<S: State> { /* ... */ state: PhantomData<S> }
struct Disconnected;
struct Connected;
struct Authenticated;

impl Connection<Disconnected> {
    fn connect(self) -> Result<Connection<Connected>> { ... }
}
impl Connection<Connected> {
    fn authenticate(self, creds: &Credentials) -> Result<Connection<Authenticated>> { ... }
}
impl Connection<Authenticated> {
    fn query(&self, sql: &str) -> Result<Rows> { ... }
}
// Can't call query() on a Disconnected connection — compile error

When to use: Protocols with clear state transitions (connections, workflows, parsing stages). When to skip: Simple on/off states — a boolean or enum is clearer.

Trait Objects vs Generics

ApproachDispatchBinary SizeFlexibility
impl Trait (generics)Static (monomorphized)Larger (one copy per type)Known at compile time
dyn Trait (trait objects)Dynamic (vtable)Smaller (one copy)Extensible at runtime

Use generics when: Performance matters, types are known at compile time, you want zero-cost abstraction. Use trait objects when: You need heterogeneous collections, plugin systems, or the set of types is open-ended.

Error Handling Patterns

PatternWhenCrate
thiserrorLibrary errors — structured, specific variantsthiserror
anyhowApplication errors — context-rich, propagate quicklyanyhow
Custom enumWhen you need exhaustive matching by callersstd only

Rule of thumb: Libraries use thiserror (callers need to match). Applications use anyhow (callers need context).


TypeScript / React Patterns

Compound Components

Components that work together implicitly via shared context.

<Select>
  <Select.Trigger>Choose a fruit</Select.Trigger>
  <Select.Options>
    <Select.Option value="apple">Apple</Select.Option>
    <Select.Option value="banana">Banana</Select.Option>
  </Select.Options>
</Select>

When to use: Complex UI components with multiple related parts (menus, accordions, tabs). When to skip: Simple components with 1-2 elements.

Custom Hook Composition

Extract and compose behavior into reusable hooks.

function useDebounce<T>(value: T, delay: number): T { ... }
function usePagination(items: Item[], pageSize: number) { ... }
function useLocalStorage<T>(key: string, initial: T) { ... }

When to use: Shared stateful logic across components, complex state management within a component. When to skip: One-off logic that doesn't repeat.

Discriminated Unions

Type-safe state modeling using TypeScript's union types.

type AsyncState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: Error };

// Exhaustive switch — TypeScript ensures all cases handled
function render(state: AsyncState<User>) {
  switch (state.status) {
    case "idle": return <Placeholder />;
    case "loading": return <Spinner />;
    case "success": return <UserCard user={state.data} />;
    case "error": return <ErrorBanner error={state.error} />;
  }
}

When to use: State machines, API response states, form states, anything with distinct modes. When to skip: Boolean flags are fine for simple on/off states.

State Management Decision Tree

  1. UI-local state? -> useState / useReducer
  2. Shared between siblings? -> Lift state to common parent
  3. Shared across distant components? -> React Context
  4. Complex state logic? -> useReducer + Context
  5. Server state (API data)? -> TanStack Query / SWR
  6. Global app state? -> Zustand / Jotai (prefer over Redux for new projects)

Django / Python Patterns

Service Layer

Separate business logic from views and models.

# services/order_service.py
class OrderService:
    @staticmethod
    def create_order(user: User, items: list[CartItem]) -> Order:
        """Business logic lives here, not in the view."""
        order = Order.objects.create(user=user, total=calculate_total(items))
        OrderItem.objects.bulk_create([...])
        send_confirmation_email(user, order)
        return order

When to use: Business logic that involves multiple models, external calls, or complex validation. When to skip: Simple CRUD with no business rules beyond Django's built-in validation.

Repository Pattern (QuerySet Abstraction)

Custom managers and querysets to encapsulate query logic.

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(status="published")

class Article(models.Model):
    objects = models.Manager()  # Default
    published = PublishedManager()  # Article.published.all()

When to use: Complex or reusable query logic, domain-specific filtering. When to skip: One-off queries or simple filters.

Signals vs Explicit Calls

ApproachProsCons
Django signalsDecoupled, works across appsHidden control flow, hard to debug, ordering issues
Explicit callsVisible, debuggable, testableCoupling between modules

Rule of thumb: Use signals for truly cross-cutting concerns (audit logging, cache invalidation). Use explicit calls for business-critical logic where you need to understand and test the flow.


Anti-Patterns (All Stacks)

Anti-PatternProblemFix
Premature abstractionAbstracting before seeing the pattern repeatWait for 3 instances before extracting
Inheritance over compositionDeep inheritance hierarchies, fragile base classPrefer composition (traits, hooks, mixins)
God objectOne class/module that does everythingSplit by responsibility (SRP)
Shotgun surgeryOne change requires editing many filesGroup related code together
Feature envyA function uses another class's data more than its ownMove the function to the class it envies
Speculative generalityBuilding for use cases that may never comeYAGNI — build for now, refactor when needed
Golden hammerUsing the same pattern/tool for everythingChoose the right tool for the job

Pattern Selection Guide

When asked "which pattern should I use?":

  1. Describe the problem (not the pattern you think fits)
  2. Identify constraints (performance, extensibility, team size, timeline)
  3. Present 2-3 options with trade-offs
  4. Recommend one with clear justification
  5. Note when to revisit — "If X changes, reconsider Y"

Integration

Cross-reference this pack's code-architect skill for structural/architecture assessment and code-quality for the complexity thresholds that motivate refactoring toward a pattern.

FAQ

What does the design-patterns skill do?

Agents should invoke this skill when choosing patterns, designing traits/interfaces/components, deciding abstraction boundaries, evaluating dependency injection/callbacks, or comparing implementation approaches in Rust, TypeScript/React, or Django/Python.

How do I install design-patterns?

Run npx skills add https://github.com/waybarrios/opencode-power-pack --skill design-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/design-patterns/ (personal) or .claude/skills/design-patterns/ (project).

Which AI agents can use design-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is design-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains design-patterns?

It is published by waybarrios in waybarrios/opencode-power-pack. It has 52 recorded installs.

More from waybarrios/opencode-power-pack

View all →

security-review

waybarrios/opencode-power-pack

Perform a focused security review of pending git changes to identify high-confidence security vulnerabilities with real exploitation potential. Use this skill when the user asks for a security review, security audit, vulnerability scan, or wants to check pending changes on a branch for security issues before merging. This is NOT a general code review.

Security750 installs

code-review

waybarrios/opencode-power-pack

Review a pull request or a set of code changes for bugs, logic errors, and project-convention violations using a confidence-filtered, multi-agent process. Use this skill when the user asks to review a PR, audit pending changes, or inspect a diff for problems before merging.

agents-md-improver

waybarrios/opencode-power-pack

Audit and improve project-rules files (AGENTS.md, CLAUDE.md, .agents/instructions, local overrides) so the agent keeps accurate project context. Use when the user asks to check, audit, review, update, improve, or fix their AGENTS.md or CLAUDE.md, mentions "project rules maintenance" or "agent context optimization", or when the codebase has changed enough that the rules file may be stale. Scans the repository for every rules file, grades each against a quality rubric, outputs a quality report, and applies targeted edits only after user approval.

code-explorer

waybarrios/opencode-power-pack

Deeply analyze an existing codebase feature by tracing execution paths, mapping architecture layers, understanding patterns and abstractions, and documenting dependencies. Use this skill when you need to understand how a feature works before modifying or extending it, when dispatched as a sub-task during feature-dev exploration, or when the user asks "how does X work in this codebase".

frontend-design

waybarrios/opencode-power-pack

Open the skill to read its SKILL.md instructions.

Frontend & Design131 installs

feature-dev

waybarrios/opencode-power-pack

Guide a feature implementation through a structured seven-phase workflow with deep codebase understanding, clarifying questions, parallel architecture design, and quality review. Use this skill when the user asks to build a new feature, add functionality, or wants a methodical approach to implementation rather than diving straight to code.

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs