> For the complete documentation index, see [llms.txt](https://blog.cweihang.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blog.cweihang.io/python/design.md).

# 设计模式

原文链接：<http://www.oschina.net/question/107361_25331>

## 单例模式

Python 的单例模式最好不要借助类（在 Java 中借助类是因为 Java 所有代码都要写在类中），而是通过一个模块来实现。一个模块的模块内全局变量、模块内全局函数，组合起来就是一个单例对象了。

## 模板方法模式

这个可以像其他语言一样实现，但是如果要遵循鸭子类型原则的话，应该删除公有的抽象父类（或接口），从而追求灵活性。

## 工厂方法模式、多例模式

这个也不用借助类，直接写一个全局函数作为工厂函数即可。因为 Python 中实例化是通过 call 类来完成的，现在改成 call 工厂函数，对客户抠码者是透明的。（从这点我表示理解 Python 没有 new 操作符的好处了，使用通用的 call 定义，正交性极强）

## 装饰器模式、代理模式

这个接触过 Python 就不会不知道了，Python 内置的 decorator 语法如此著名。装饰器模式和代理模式都可以通过这种方式完成。另外一种是对对象的装饰或代理，这个也不需要按照契约编程的风格，让代理对象实现被代理对象的抽象。一切动态代理，只需要通过重载属性访问操作符，神马都简单了（和 PHP 通过 **get、**&#x73;et、\_\_call 来实现动态代理很类似）。

## 原型模式

这个在 Python 中实现的不是那么爽快，需要调用 copy 来克隆原型对象。但是其实有另一种实现方式：之所以使用原型模式，是因为对象初始化需要较大开销。我们只需要保存初始化的结果，并在产生新对象的时候赋予新对象即可。所以，通过元类控制对象被创建的过程，来实现原型模式，也是一种选择。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.cweihang.io/python/design.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
