Logo Design Patterns

Design Patterns

Cộng đồng
j4flmao
design-patterns

Use this skill when selecting or reviewing any design pattern — GoF creational/structural/behavioral, enterprise, integration, concurrency, architectural, or anti-pattern avoidance. This skill enforces: pattern selection decision framework, trade-off analysis, anti-pattern rejection, explicit elimination criteria for rejected candidates, and pattern composition rules. Do NOT use for: framework-specific patterns (e.g. Angular DI), language-specific idioms (e.g. Rust ownership), infrastructure patterns (e.g. Kubernetes operators).

Tổng quan

Nhà phát hànhj4flmao
Kho mãagent-skills
Tên kỹ năngdesign-patterns
Sao
41
Bản fork
6
Tệp đi kèm
12
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 12 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được j4flmao công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Design Patterns trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/universal/design-patterns .claude/skills/design-patterns
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Design Patterns trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Design Patterns ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Design Patterns không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Design Patterns

Purpose

Guide pattern selection across all categories — GoF, enterprise, integration, concurrency, architectural — with decision trees, applicability rules, trade-off analysis, and composition guidance.

Agent Protocol

Trigger

User request includes: design pattern, gof, gang of four, pattern catalog, creational, structural, behavioral, pattern selection, enterprise pattern, integration pattern, concurrency pattern, architectural pattern, anti-pattern, pattern composition, CQRS, event sourcing, saga, repository, unit of work, messaging pattern, circuit breaker, strangler fig, saga pattern, hexagonal architecture, clean architecture.

Input Context

  • Problem statement with constraints (performance, memory, team size, tech stack)
  • Current architecture description
  • Existing patterns already in use
  • Pattern category preference or openness

Output Artifact

Selected pattern(s) with rationale, rejected candidates with explicit elimination reasons, implementation sketch, trade-off table, and composition rules if multiple patterns are needed.

Response Format

No preamble. No postamble. No explanations. Strip articles a/an/the where unambiguous. Compress output. If no pattern fits, output No matching pattern. Consider: [alternative approach]. and stop.

Completion Criteria

  • Decision tree traversed and documented
  • Rejected candidates include explicit elimination reason
  • Implementation sketch covers pattern structure (not full business logic)
  • Trade-offs documented for each selected pattern
  • Pattern composition rules applied if multiple patterns

Architecture Decision Tree

Which Pattern Category?

What kind of problem are you solving?
  ├── Object creation, instance management → Creational (Singleton, Factory, Builder, Prototype)
  ├── Class/object composition, interfaces → Structural (Adapter, Decorator, Proxy, Facade)
  ├── Object communication, algorithms → Behavioral (Observer, Strategy, Command, State)
  ├── Business logic organization, persistence → Enterprise (Repository, Unit of Work, Aggregate)
  ├── Service-to-service communication → Integration (Message Queue, Event Bus, API Gateway)
  ├── Thread safety, async coordination → Concurrency (Mutex, Semaphore, Actor, Fan-out/Fan-in)
  ├── High-level system structure → Architectural (Clean Architecture, Hexagonal, CQRS, Event Sourcing)
  └── Code smells affecting maintainability → Anti-Pattern to refactor (God Class, Spaghetti Code)

GoF Pattern Selection Decision Tree

What is changing?
  ├── How objects are created → Creational
  │   ├── Need to ensure single instance → Singleton
  │   ├── Need to create families of related objects → Abstract Factory
  │   ├── Need to construct complex objects step by step → Builder
  │   ├── Need to create copies without knowing concrete types → Prototype
  │   └── Need to delegate creation to subclasses → Factory Method
  ├── How objects are composed → Structural
  │   ├── Need to make incompatible interfaces compatible → Adapter
  │   ├── Need to add responsibilities dynamically → Decorator
  │   ├── Need to control access to an object → Proxy
  │   ├── Need to simplify complex subsystem → Facade
  │   ├── Need to compose objects into tree structures → Composite
  │   └── Need to share fine-grained objects → Flyweight (only if profiler confirms memory pressure)
  └── How objects communicate and distribute work → Behavioral
      ├── Need to notify multiple objects of state changes → Observer
      ├── Need to select algorithm at runtime → Strategy
      ├── Need to encapsulate a request as an object → Command
      ├── Need to define skeleton of an algorithm → Template Method
      ├── Need to traverse a collection without exposing internals → Iterator
      ├── Need to represent a grammar → Interpreter
      ├── Need to capture and restore object state → Memento
      ├── Need to dispatch operations based on type → Visitor
      └── Need to manage state-dependent behavior → State

Enterprise Pattern Selection

What enterprise problem are you solving?
  ├── Data access abstraction → Repository
  ├── Transaction coordination → Unit of Work
  ├── Business logic as transaction script → Transaction Script
  ├── Business logic as domain model → Domain Model
  ├── Object identity and caching → Identity Map
  ├── Lazy loading for related objects → Lazy Load
  ├── Mapping objects to database → Data Mapper
  └── Separating read/write models → CQRS

Integration Pattern Selection

How do services communicate?
  ├── One-to-one, request-reply → RPC/HTTP + Circuit Breaker
  ├── One-to-many, fire-and-forget → Message Queue (Event Bus)
  ├── Guaranteed delivery, durability → Durable Message Queue
  ├── Bidirectional, low latency → WebSocket
  ├── Asynchronous, eventual consistency → Event-Driven + Transactional Outbox
  ├── Coordinating multiple services → Saga (Choreography or Orchestration)
  ├── Gradually migrating a monolith → Strangler Fig
  └── Protecting downstream services → Circuit Breaker + Retry + Bulkhead

Concurrency Pattern Selection

What concurrency problem?
  ├── Protect shared resource → Mutex / Read-Write Lock
  ├── Coordinate multiple workers → Semaphore / Barrier
  ├── Pipeline processing → Pipeline / Fan-out/Fan-in
  ├── Thread-safe state management → Actor Model
  └── Parallel independent tasks → Fork-Join / Parallel Streams

Workflow

Step 1: Classify the Problem

ProblemCategoryReference
Object creation, instance managementCreationalgof-patterns.md
Class/object composition, interfacesStructuralgof-patterns.md
Object communication, algorithmsBehavioralgof-patterns.md
Business logic organization, persistenceEnterpriseenterprise-patterns.md
Service-to-service communicationIntegrationintegration-patterns.md
Thread safety, async coordinationConcurrencyconcurrency-patterns.md
High-level system structureArchitecturalenterprise-patterns.md
Code smells needing refactoringAnti-patternsanti-patterns.md

Step 2: Apply Selection Decision Framework

  1. What is changing? (axis of change) — patterns encapsulate change
  2. What is binding time? (compile-time vs runtime)
  3. What is scope? (class-level vs object-level)

Step 3: Evaluate Candidates Within Category

For each candidate pattern, evaluate:

  • Intent match: Does the pattern's intent solve the stated problem?
  • Applicability: Are the conditions for using this pattern met?
  • Trade-offs: What does the pattern cost (complexity, indirection, performance)?
  • Composition: Does this pattern combine well with others?

Pattern Implementation Examples

Factory Method (TypeScript)

typescript
interface PaymentGateway {
  charge(amount: Money): Promise<PaymentResult>;
}

class StripeGateway implements PaymentGateway { ... }
class PayPalGateway implements PaymentGateway { ... }

abstract class PaymentGatewayFactory {
  abstract createGateway(): PaymentGateway;
  
  async processPayment(amount: Money): Promise<PaymentResult> {
    const gateway = this.createGateway();
    return gateway.charge(amount);
  }
}

class StripeFactory extends PaymentGatewayFactory {
  createGateway(): PaymentGateway {
    return new StripeGateway(process.env.STRIPE_KEY);
  }
}

Strategy Pattern (Python)

python
from abc import ABC, abstractmethod

class ShippingStrategy(ABC):
    @abstractmethod
    def calculate(self, weight: float, distance: float) -> float: ...

class FlatRateShipping(ShippingStrategy):
    def calculate(self, weight: float, distance: float) -> float:
        return 5.99

class WeightBasedShipping(ShippingStrategy):
    def calculate(self, weight: float, distance: float) -> float:
        return weight * 0.5 + distance * 0.01

class Order:
    def __init__(self, shipping_strategy: ShippingStrategy):
        self._shipping = shipping_strategy
    
    @property
    def shipping_cost(self) -> float:
        return self._shipping.calculate(self.weight, self.distance)

Observer Pattern (Event-Driven)

typescript
interface Observer<T> {
  update(event: T): Promise<void>;
}

class EventEmitter<T> {
  private observers: Set<Observer<T>> = new Set();

  subscribe(observer: Observer<T>): void {
    this.observers.add(observer);
  }

  unsubscribe(observer: Observer<T>): void {
    this.observers.delete(observer);
  }

  async emit(event: T): Promise<void> {
    await Promise.allSettled(
      Array.from(this.observers).map(o => o.update(event))
    );
  }
}

Decorator Pattern (TypeScript)

typescript
interface Notifier {
  send(message: string): Promise<void>;
}

class EmailNotifier implements Notifier {
  async send(message: string): Promise<void> {
    // Send via SMTP
  }
}

class SlackNotifierDecorator implements Notifier {
  constructor(private wrapped: Notifier) {}

  async send(message: string): Promise<void> {
    await this.wrapped.send(message);
    await this.sendToSlack(message);  // additional behavior
  }

  private async sendToSlack(message: string): Promise<void> {
    // Post to Slack channel
  }
}

Adapter Pattern (Third-Party Integration)

typescript
// Third-party SDK (incompatible interface)
class StripeSDK {
  createPayment(amountCents: number, currency: string, token: string): Promise<any> { }
}

// Target interface
interface PaymentProcessor {
  charge(amount: Money): Promise<PaymentResult>;
}

// Adapter
class StripeAdapter implements PaymentProcessor {
  constructor(private sdk: StripeSDK) {}

  async charge(amount: Money): Promise<PaymentResult> {
    const response = await this.sdk.createPayment(
      amount.toCents(),
      amount.currency,
      amount.sourceToken
    );
    return { transactionId: response.id, status: response.status };
  }
}

Command Pattern (CQRS)

typescript
interface Command<T = void> {
  execute(): Promise<T>;
}

class PlaceOrderCommand implements Command<Order> {
  constructor(
    private orderRepo: OrderRepository,
    private eventBus: EventBus,
    private items: OrderItem[],
  ) {}

  async execute(): Promise<Order> {
    const order = Order.create(this.items);
    await this.orderRepo.save(order);
    await this.eventBus.publish(new OrderPlacedEvent(order.id));
    return order;
  }
}

// Usage
const command = new PlaceOrderCommand(repo, bus, items);
await commandBus.dispatch(command);

State Pattern (State Machine)

typescript
interface OrderState {
  addItem(item: OrderItem): void;
  pay(amount: Money): void;
  ship(): void;
}

class PendingState implements OrderState {
  constructor(private order: Order) {}
  addItem(item: OrderItem) { this.order.items.push(item); }
  pay(amount: Money) { this.order.setState(new PaidState(this.order)); }
  ship() { throw new Error('Cannot ship pending order'); }
}

class PaidState implements OrderState {
  constructor(private order: Order) {}
  addItem() { throw new Error('Cannot modify paid order'); }
  pay() { throw new Error('Already paid'); }
  ship() { this.order.setState(new ShippedState(this.order)); }
}

class Order {
  state: OrderState = new PendingState(this);
  setState(state: OrderState) { this.state = state; }
}

Anti-Patterns and Rejections

Common Anti-Patterns to Reject

Anti-PatternProblemBetter Alternative
SingletonGlobal state, hidden dependenciesDI-managed single instance
God ClassToo many responsibilitiesDecompose into smaller classes
Spaghetti CodeUnstructured flowClean Architecture layers
Golden HammerApplying familiar pattern everywhereMatch pattern to problem
Premature OptimizationOptimizing without profilingMeasure first, optimize later
Service LocatorHidden dependenciesConstructor injection

Pattern Composition

Common Compositions

CompositionPatternsUse Case
Repository + Unit of WorkEnterpriseData access with transaction coordination
Command + Observer + MediatorBehavioral + BehavioralCQRS with event bus
Strategy + FactoryBehavioral + CreationalPluggable algorithms with auto-selection
Decorator + ProxyStructural + StructuralLayered cross-cutting concerns
Adapter + FactoryStructural + CreationalThird-party integration abstraction
Saga + CQRS + Event SourcingArchitectural + ArchitecturalDistributed transactions with audit
Chain of Responsibility + CompositeBehavioral + StructuralRequest processing pipeline

Performance Considerations

  • Decorator pattern adds N method calls per operation — acceptable for I/O (< 1μs per layer)
  • Observer pattern with many subscribers — use batched delivery or async processing
  • Reflection-based patterns (DI, ORM) add startup cost — acceptable for server apps
  • Flyweight only when profiler confirms memory pressure
  • Command pattern with many commands — use command bus with async dispatch

Security Considerations

  • Proxy pattern for access control (validation proxy, audit proxy)
  • Strategy pattern for role-based algorithm selection
  • Template Method for secure base implementation with overridable hooks
  • Factory pattern for input validation before object creation
  • Command pattern enables security audit trail (every action is an object)

Rules

  • Identify axis of change before selecting pattern.
  • Prefer composition over inheritance.
  • Singleton only when DI cannot manage lifecycle.
  • Flyweight only when profiler confirms memory pressure.
  • No pattern is universally applicable — context determines fitness.
  • Enterprise patterns solve business logic organization.
  • Integration patterns solve service communication.
  • Concurrency patterns add complexity — use only when profiler confirms contention.
  • Architectural patterns constrain the entire system — apply early, refactor reluctantly.
  • Every pattern selection must document rejected alternatives with reasons.
  • When two patterns solve the same problem, pick the simpler one.
  • Never apply a pattern just because it exists — always have a concrete problem.

References

  • references/anti-patterns.md — Anti-Patterns Reference
  • references/concurrency-patterns.md — Concurrency Patterns
  • references/design-patterns-fundamentals.md — Design Patterns Fundamentals
  • references/behavioral_patterns.md — Behavioral Patterns
  • references/domain-driven-design-patterns.md — Domain-Driven Design Patterns
  • references/enterprise-patterns.md — Enterprise & Architectural Patterns
  • references/gof-patterns.md — GoF Design Patterns Reference
  • references/integration-patterns.md — Enterprise Integration Patterns Reference
  • references/structural_patterns.md — Structural Patterns
  • references/pattern-relationships.md — Pattern Relationships & Selection Reference
  • references/selection-decision-tree.md — Pattern Selection Decision Tree
  • references/testing-patterns.md — Testing Design Patterns

Shared References

Additional reference material for this skill, stored outside its own references/ folder.

  • ../oop-principles/references/composition-vs-inheritance.md — Composition over Inheritance
  • ../oop-principles/references/cpp_vtables_theory.md — C++ Virtual Dispatch: vtables and vptrs
  • ../oop-principles/references/grasp-patterns.md — GRASP Patterns
  • ../oop-principles/references/object_memory_layout.md — C++ Object Memory Layout and Inheritance
  • ../oop-principles/references/oop-solid.md — OOP SOLID Principles
  • ../oop-principles/references/principles-reference.md — Principles Reference
  • ../oop-principles/references/solid-deep-dive.md — SOLID Deep Dive
  • ../oop-principles/references/solid-examples.md — SOLID Code Examples

Handoff

Hand off to backend/universal/microservices/SKILL.md if distributed system patterns need implementation details. Hand off to backend/universal/clean-architecture/SKILL.md if structuring the entire application. Hand off to backend/universal/event-driven/SKILL.md if event-driven patterns need elaboration.

  • Review code for security, performance, and correctness before merging.

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Design Patterns làm được gì?

Use this skill when selecting or reviewing any design pattern — GoF creational/structural/behavioral, enterprise, integration, concurrency, architectural, or anti-pattern avoidance. This skill enforces: pattern selection decision framework, trade-off analysis, anti-pattern rejection, explicit elimination criteria for rejected candidates, and pattern composition rules. Do NOT use for: framework-specific patterns (e.g. Angular DI), language-specific idioms (e.g. Rust ownership), infrastructure patterns (e.g. Kubernetes operators).

Vì sao nên dùng Design Patterns trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Design Patterns là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Design Patterns trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Design Patterns?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Design Patterns với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Design Patterns với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Design Patterns có miễn phí không?

Có. Kỹ năng này được j4flmao phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇