Python 设计模式概述
设计模式(Design Patterns)是软件设计中常见的、可复用的问题解决方案,由 GoF(Gang of Four,四人组)在1994年的经典书籍《设计模式:可复用面向对象软件的基础》中总结出23种模式。这些模式分为三大类:创建型(Creational)、结构型(Structural)和行为型(Behavioral)。
在 Python 中,由于语言的动态特性(如鸭子类型、装饰器、内置迭代器等),有些模式实现更简单,甚至某些模式(如迭代器、装饰器)已被语言内置。但掌握这些模式有助于写出更优雅、可维护的代码,尤其在大型项目中。
三大类设计模式列表
| 类别 | 模式名称(中文/英文) | 主要用途 |
|---|---|---|
| 创建型(5种) | 单例模式 (Singleton) 工厂方法 (Factory Method) 抽象工厂 (Abstract Factory) 生成器 (Builder) 原型 (Prototype) | 处理对象创建方式,隐藏创建细节,提高灵活性。 |
| 结构型(7种) | 适配器 (Adapter) 桥接 (Bridge) 组合 (Composite) 装饰器 (Decorator) 外观 (Facade) 享元 (Flyweight) 代理 (Proxy) | 处理类或对象的组合,简化结构,提高复用。 |
| 行为型(11种) | 责任链 (Chain of Responsibility) 命令 (Command) 解释器 (Interpreter) 迭代器 (Iterator) 中介者 (Mediator) 备忘录 (Memento) 观察者 (Observer) 状态 (State) 策略 (Strategy) 模板方法 (Template Method) 访问者 (Visitor) | 处理对象间的交互和责任分配,提高解耦。 |
常见模式 Python 示例
下面挑选几个经典模式,提供简洁的 Python 实现示例(基于 Python 3+)。
单例模式 (Singleton)
确保一个类只有一个实例,常用于数据库连接、日志器等。classSingleton:_instance=Nonedef__new__(cls,*args,**kwargs):ifcls._instanceisNone:cls._instance=super().__new__(cls)returncls._instance# 使用s1=Singleton()s2=Singleton()print(s1iss2)# True工厂方法 (Factory Method)
定义创建接口,让子类决定实例化哪个类。fromabcimportABC,abstractmethodclassProduct(ABC):@abstractmethoddefoperation(self):passclassConcreteProductA(Product):defoperation(self):return"Product A"classConcreteProductB(Product):defoperation(self):return"Product B"classCreator(ABC):@abstractmethoddeffactory_method(self):passdefsome_operation(self):product=self.factory_method()returnf"Creator:{product.operation()}"classConcreteCreatorA(Creator):deffactory_method(self):returnConcreteProductA()# 使用creator=ConcreteCreatorA()print(creator.some_operation())# Creator: Product A观察者模式 (Observer)
一对多依赖,当主体变化时通知观察者(常用于事件系统)。classSubject:def__init__(self):self._observers=[]defattach(self,observer):self._observers.append(observer)defnotify(self):forobserverinself._observers:observer.update(self)classObserver:defupdate(self,subject):print(f"Observer notified:{subject}")# 使用subject=Subject()observer=Observer()subject.attach(observer)subject.notify()# Observer notified: <__main__.Subject object at ...>装饰器模式 (Decorator)
动态添加职责(Python 有内置 @decorator 语法)。defdecorator(func):defwrapper(*args,**kwargs):print("Before call")result=func(*args,**kwargs)print("After call")returnresultreturnwrapper@decoratordefgreet(name):returnf"Hello,{name}!"print(greet("World"))# Before/After + Hello, World!
注意事项
- Python 的动态性使一些模式(如策略模式)可以用简单函数实现,而非类。
- 不要滥用模式:遵循 KISS(Keep It Simple, Stupid)和 YAGNI(You Aren’t Gonna Need It)原则。
- 推荐资源:
- Refactoring Guru(中文版):https://refactoringguru.cn/design-patterns/python (详细代码示例)。
- GitHub 项目:faif/python-patterns(经典实现集合)。
- 书籍:《Mastering Python Design Patterns》或 GoF 原书结合 Python 示例。
如果需要某个具体模式的详细解释、更多代码或应用场景,请告诉我!