agentleFS
28672032962867203296/hermes-agent/skills/software-development/python-design-patterns/SKILL.md

python-design-patterns

Skill0 starsChanged 3 months agoMITView on GitHub

Python设计模式实战:创建型、结构型、行为型,附代码.

16 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use python-type-safety, python-error-handling and 7 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.
  • CodeWithBehnamSkill

    python-type-safety

    Python type safety with type hints, generics, protocols, and strict type checking. Use when adding type annotations, implementing generic classes, defining structural interfaces, or configuring mypy/pyright.

    Also in 5 projects that use this

  • justanestaSkill

    python-error-handling

    Python error handling and debugging. Use this skill when implementing error handling, designing exception hierarchies, debugging issues, or adding logging. Covers exception patterns, custom exceptions, logging with structlog, debugging tools, and error recovery.

    Also in 4 projects that use this

  • CodeWithBehnamSkill

    python-anti-patterns

    Common Python anti-patterns to avoid. Use as a checklist when reviewing code, before finalizing implementations, or when debugging issues that might stem from known bad practices.

    Also in 4 projects that use this

  • xfstudioSkill

    python-testing-patterns

    Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.

    Also in 7 projects that use this

  • nilecuiSkill

    async-python-patterns

    Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.

    Also in 4 projects that use this

  • xfstudioSkill

    javascript-testing-patterns

    Implement comprehensive testing strategies using Jest, Vitest, and Testing Library for unit tests, integration tests, and end-to-end testing with mocking, fixtures, and test-driven development. Use when writing JavaScript/TypeScript tests, setting up test infrastructure, or implementing TDD/BDD workflows.

    Also in 3 projects that use this

  • +1 more from CodeWithBehnam
  • +2 more from xfstudio

The file

Files
SKILL.md

Python 设计模式

借鉴 faif/python-patterns (43k⭐)。

创建型模式(怎么创建对象)

单例 Singleton

class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

场景:配置管理、日志器、数据库连接池。

工厂 Factory

class AnimalFactory:
    @staticmethod
    def create(animal_type):
        if animal_type == "dog": return Dog()
        if animal_type == "cat": return Cat()
        raise ValueError(f"Unknown: {animal_type}")

场景:根据配置/输入创建不同对象,调用者不关心具体类。

建造者 Builder

class Pizza:
    def __init__(self): self.toppings = []
    def add_topping(self, t): self.toppings.append(t); return self

pizza = Pizza().add_topping("奶酪").add_topping("蘑菇")

场景:参数太多或构造步骤复杂时,链式调用优雅。

对象池 Pool

class ConnectionPool:
    def __init__(self, size=5):
        self._pool = [create_connection() for _ in range(size)]
    def acquire(self): return self._pool.pop()
    def release(self, conn): self._pool.append(conn)

场景:数据库连接、线程池,避免反复创建销毁。

结构型模式(怎么组织类和对象)

适配器 Adapter

class USBToTypeC:
    def __init__(self, usb_device):
        self._device = usb_device
    def connect_type_c(self):
        return self._device.connect_usb()

场景:对接不同接口的第三方库。

装饰器 Decorator

def log_call(func):
    def wrapper(*a, **kw):
        print(f"调用 {func.__name__}")
        return func(*a, **kw)
    return wrapper

@log_call
def do_stuff(): pass

场景:加日志/计时/权限检查,不改原函数。

代理 Proxy

class LazyImage:
    def __init__(self, path):
        self._path = path; self._img = None
    def show(self):
        if self._img is None:
            self._img = load_image(self._path)  # 用时才加载
        self._img.show()

场景:延迟加载、访问控制、远程代理。

行为型模式(对象怎么交互)

观察者 Observer

class EventBus:
    def __init__(self): self._handlers = {}
    def on(self, event, handler):
        self._handlers.setdefault(event, []).append(handler)
    def emit(self, event, data):
        for h in self._handlers.get(event, []): h(data)

场景:GUI事件、消息通知、发布-订阅。

策略 Strategy

class Sorter:
    def __init__(self, strategy): self._s = strategy
    def sort(self, data): return self._s(data)

Sorter(quick_sort).sort(data)  # 可换算法
Sorter(merge_sort).sort(data)

场景:算法可替换,运行时选策略。

状态 State

class Order:
    def __init__(self):
        self._states = {"pending": Pending(), "paid": Paid(), "shipped": Shipped()}
        self._current = self._states["pending"]
    def pay(self): self._current = self._states["paid"]

场景:订单状态、工作流、游戏状态机。

命令 Command

class Undoable:
    def execute(self): pass
    def undo(self): pass

class InsertCommand(Undoable):
    def execute(self): doc.insert(text)
    def undo(self): doc.delete(text)

场景:撤销/重做、任务队列、宏录制。

选型原则

对象创建复杂?→ 创建型(工厂/建造者/池)
接口不兼容?  → 结构型(适配器/装饰器/代理)
对象协作复杂?→ 行为型(观察者/策略/状态/命令)

不要为了用模式而用模式——先有痛点,再找模式。

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.