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
- rotnov/pycctheir own version, first seen Nov 22, 2026
- zebbern/pocmaptheir own version, first seen Nov 8, 2026
- delorenj/skillstheir own version, first seen Nov 7, 2026
- nledford/engineering-review-boardtheir own version, first seen Nov 3, 2026
- NorkzYT/claude-code-autopilottheir own version, first seen Oct 25, 2026
- scwf/feishuai-skillstheir own version, first seen Oct 25, 2026
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.
CodeWithBehnamSkillpython-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
justanestaSkillpython-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
CodeWithBehnamSkillpython-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
xfstudioSkillpython-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
nilecuiSkillasync-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
xfstudioSkilljavascript-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
Other versions16 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 16
- delorenj/skills★ 17same name
- nledford/engineering-review-board★ 11same name
- zebbern/pocmap★ 7same name
- GPTtang/skill-atlas★ 4same name
- scwf/feishuai-skills★ 4same name
- zebbern/termstack★ 4same name
- Aver005/agent-skills★ 2same name
- CodeWithBehnam/cc-docs★ 2same name
- roshankodi/agent-skills★ 2same name
- rotnov/pycc★ 2same name
6 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository219 other files it gives its agents.
- agent-doctrineSkill
- agent-evaluation-frameworkSkill
- agent-visualization-flintSkill
- hermes-agentSkill
- bailian-cliSkill
- edge-browser-automationSkill
- computer-useSkill
- jupyter-live-kernelSkill
- backup-strategiesSkill
- browser-automationSkill
- chinese-ai-free-apiSkill
- cicd-pipeline-templatesSkill
- copybaraSkill
- devops-toolkitSkill
- email-deliverabilitySkill
- monitoring-observabilitySkill
- obsidian-maintenanceSkill
- obsidian-troubleshootingSkill
- openclaw-windowsSkill
- openclaw-workerSkill
- webhook-subscriptionsSkill
- windows-dev-environmentSkill
- windows-masterSkill
- zero-downtime-deploySkill
- codebase-inspectionSkill
- github-workflowSkill
- adaptive-communicationSkill
- agent-cost-dashboardSkill
- agent-evolutionSkill
- agent-governanceSkill
- agent-osSkill
- context-efficient-toolsSkill
- context-loss-awarenessSkill
- creative-synthesisSkill
- hermes-desktop-pluginsSkill
- emotional-intelligenceSkill
- graph-engineering-workflowSkill
- hermes-maintenanceSkill
- hermes-voiceSkill
- hermes-hygieneSkill
- identity-coreSkill
- income-loopSkill
- master-synthesisSkill
- meta-cognitionSkill
- reasoning-engineSkill
- self-preservationSkill
- teaching-abilitySkill
- temporal-awarenessSkill
- hermes-themesSkill
- thinking-visualizationSkill
- user-modelingSkill
- voice-full-restoreSkill
- knowledge-graph-traversalSkill
- mcp-browser-canvasSkill
- free-api-gatewaySkill
- native-mcpSkill
- web-reverse-apiSkill
- ai-edaSkill
- huggingface-hubSkill
- industrial-ai-siemens-mcpSkill
- The first 60 shown.
The file
Files
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)场景:撤销/重做、任务队列、宏录制。
选型原则
对象创建复杂?→ 创建型(工厂/建造者/池)
接口不兼容? → 结构型(适配器/装饰器/代理)
对象协作复杂?→ 行为型(观察者/策略/状态/命令)
不要为了用模式而用模式——先有痛点,再找模式。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
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.

