agentleFS
Khuirul-HudaKhuirul-Huda/clean-principles/skills/design-patterns/SKILL.md

design-patterns

Skill0 starsChanged 29 days agoMITView on GitHub

Use when solving recurring structural or behavioral design problems — recognizing when code needs a proven pattern like factory, observer, strategy, or repository.

33 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use logging-patterns, tdd-rust and 9 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • DIL8654Skill

    logging-patterns

    Keep logs structured, correlated, low-noise, and safe for production support. Use when adding operational logging, reviewing observability, or improving diagnostics in .NET services.

    Also in 7 projects that use this

  • FlorianBruniauxSkill

    tdd-rust

    Also in 3 projects that use this

  • mstuder-slalomSkill

    jpa-patterns

    JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.

    Also in 6 projects that use this

  • ufodev-ioSkill

    security-guardian

    Comprehensive security layer for all interactions with Claude: audits code, dependencies, commands, configs, and AI-generated output for vulnerabilities. Protects against prompt injection, data leaks, unsafe advice, and social engineering. Works in Cursor, Claude Code, claude.ai, and API contexts. Use always as a background security protocol in any Claude-powered environment.

    Also in 3 projects that use this

  • DIL8654Skill

    api-contract-review

    Review ASP.NET Core Web API contracts for HTTP semantics, versioning, backward compatibility, and response consistency. Use when the user asks to review an API, check endpoints, validate REST behavior, or before releasing contract changes.

    Also in 3 projects that use this

  • zavierSkill

    java-code-review

    Java代码审查技能,通过比较两个git分支进行自动化代码审查

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

1 rule. 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 32 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Problem: Add behavior without modifying the original class.

    line 85

“Common” is measured: kept by at least 6 in 10 of the 32 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Design Patterns

Proven solutions to recurring design problems. Use patterns when you recognize the problem — not to show cleverness.

Warning: Patterns add complexity. Only apply when the problem is actually recurring.

Creational — How Objects Are Created

Factory Method

Problem: Caller shouldn't know which concrete class to instantiate.

# Instead of: notification = EmailNotification(msg)
# Use: notification = NotificationFactory.create("email", msg)

class NotificationFactory:
    _registry = {"email": EmailNotification, "sms": SMSNotification}

    @classmethod
    def create(cls, type: str, message: str) -> Notification:
        if type not in cls._registry:
            raise ValueError(f"Unknown notification type: {type}")
        return cls._registry[type](message)

Builder

Problem: Object needs many optional parameters (telescoping constructor).

# Instead of: Query(table, cols, where, limit, offset, order, joins)
query = (QueryBuilder("users")
    .select("id", "name")
    .where("active = true")
    .limit(10)
    .build())

Singleton

Problem: Exactly one instance needed (config, connection pool).

class Config:
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

⚠️ The naive implementation above is NOT thread-safe. Use a lock in multi-threaded environments:

import threading
class Config:
    _instance = None
    _lock = threading.Lock()
    def __new__(cls):
        with cls._lock:
            if not cls._instance:
                cls._instance = super().__new__(cls)
        return cls._instance

⚠️ Avoid for anything testable — singletons make tests order-dependent.


Structural — How Objects Are Composed

Adapter

Problem: Make an incompatible interface work with existing code.

# Legacy system returns dict, new system expects object
class LegacyUserAdapter:
    def __init__(self, legacy_dict: dict):
        self._data = legacy_dict

    @property
    def id(self): return self._data["user_id"]
    @property
    def name(self): return self._data["full_name"]

Decorator

Problem: Add behavior without modifying the original class.

class LoggingRepository:
    def __init__(self, repo: UserRepository):
        self._repo = repo

    def find(self, id: int) -> User:
        logger.info(f"Finding user {id}")
        result = self._repo.find(id)
        logger.info(f"Found: {result}")
        return result

Repository

Problem: Decouple business logic from data access.

class UserRepository(ABC):
    @abstractmethod
    def find_by_id(self, id: int) -> User: ...
    @abstractmethod
    def save(self, user: User) -> None: ...

class SQLUserRepository(UserRepository):
    def find_by_id(self, id: int) -> User:
        row = self.db.query("SELECT * FROM users WHERE id = ?", id)
        return User.from_row(row)

Facade

Problem: Callers must coordinate a complex subsystem — simplify behind one interface.

class PaymentFacade:
    def charge(self, amount: float, card: Card) -> Receipt:
        self.fraud_detector.check(card)       # complex internals
        receipt = self.stripe.charge(amount, card)
        self.audit_logger.log(receipt)
        return receipt
# Caller only knows: facade.charge(amount, card)

Proxy

Problem: Control access to an object — add caching, auth, or lazy loading transparently.

class CachedUserRepository:
    def __init__(self, repo: UserRepository, cache: Cache):
        self._repo, self._cache = repo, cache

    def find_by_id(self, id: int) -> User:
        if user := self._cache.get(f"user:{id}"):
            return user
        user = self._repo.find_by_id(id)
        self._cache.set(f"user:{id}", user)
        return user

Behavioral — How Objects Communicate

Observer / Event

Problem: Notify multiple objects when state changes, without tight coupling.

class EventBus:
    def __init__(self):
        self._handlers: dict[str, list[Callable]] = {}

    def subscribe(self, event: str, handler: Callable): ...
    def publish(self, event: str, data: any): ...

# OrderService doesn't know about EmailService, InventoryService, etc.
event_bus.publish("order.placed", order)

Strategy

Problem: Swap algorithms at runtime.

class PaymentProcessor:
    def __init__(self, strategy: PaymentStrategy):
        self._strategy = strategy

    def charge(self, amount: float):
        self._strategy.process(amount)  # Stripe, PayPal, Crypto — all the same interface

Command

Problem: Encapsulate requests as objects (for undo/queue/logging).

class Command(ABC):
    @abstractmethod
    def execute(self): ...
    @abstractmethod
    def undo(self): ...

class MoveCommand(Command):
    def execute(self): self.piece.move(self.destination)
    def undo(self): self.piece.move(self.origin)

Template Method

Problem: An algorithm's structure is fixed, but specific steps vary per subclass.

class ReportGenerator(ABC):
    def generate(self) -> str:       # fixed skeleton — not overridable
        data = self.fetch_data()
        return self.format(data)

    @abstractmethod
    def fetch_data(self) -> list: ...

    @abstractmethod
    def format(self, data: list) -> str: ...

class CSVReport(ReportGenerator):
    def fetch_data(self): return db.query("SELECT ...")
    def format(self, data): return ",".join(str(r) for r in data)

Pattern Selection Guide

SituationPattern
Creating objects based on type/conditionFactory Method
Complex object constructionBuilder
Incompatible interfaceAdapter
Add behavior non-invasivelyDecorator
Decouple data accessRepository
Notify many listenersObserver
Swap algorithmsStrategy
Provide simple interface to complex subsystemFacade
Control/cache access to an objectProxy
Fixed algorithm with varying stepsTemplate Method
Undo/queue operationsCommand

When to Refactor TO a Pattern

Signal in your codeIntroduce
if/elif grows every time you add a new typeFactory Method
Constructor keeps gaining optional parametersBuilder
Need to add logging/caching/auth to many classesDecorator or Proxy
Multiple services react to the same eventObserver
Same algorithm, varying steps per subclassStrategy or Template Method
Caller must coordinate many subsystem callsFacade
Operations need undo or async queuingCommand

Anti-Pattern Warning

Pattern abuseSign
Factory for 1 typeJust use new
Observer with 1 subscriberJust call the method
Singleton everywhereYou're hiding global state
Strategy with 1 strategyPremature flexibility

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.