以下是 Python 中常用设计模式 的分类总结与代码示例,结合 Python 动态语言特性简化实现,涵盖创建型、结构型与行为型三大类:
一、创建型模式(Creational Patterns)
1. 单例模式(Singleton)
- 用途:确保类只有一个实例(如配置管理、日志记录)。
- Pythonic 实现:
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance # 使用 s1 = Singleton() s2 = Singleton() print(s1 is s2) # True
2. 工厂方法(Factory Method)
- 用途:解耦对象创建逻辑,允许子类决定实例化哪个类。
- 示例:
class Button: def render(self): pass class WindowsButton(Button): def render(self): return "Windows风格按钮" class MacButton(Button): def render(self): return "Mac风格按钮" class GUIFactory: def create_button(self): pass class WindowsFactory(GUIFactory): def create_button(self): return WindowsButton() class MacFactory(GUIFactory): def create_button(self): return MacButton() # 使用 factory = MacFactory() button = factory.create_button() print(button.render()) # Mac风格按钮
3. 建造者模式(Builder)
- 用途:分步构建复杂对象(如生成复杂配置或文档)。
- 链式调用实现:
class Pizza: def __init__(self): self.toppings = [] def add_topping(self, topping): self.toppings.append(topping) return self # 支持链式调用 # 使用 pizza = Pizza().add_topping("芝士").add_topping("火腿") print(pizza.toppings) # ['芝士', '火腿']
二、结构型模式(Structural Patterns)
1. 适配器模式(Adapter)
- 用途:转换接口以兼容不同类(如旧系统整合)。
- 示例:
class OldSystem: def legacy_request(self): return "旧系统数据" class Adapter: def __init__(self, old_system): self.old_system = old_system def new_request(self): return f"适配后: {self.old_system.legacy_request()}" # 使用 adapter = Adapter(OldSystem()) print(adapter.new_request()) # 适配后: 旧系统数据
2. 装饰器模式(Decorator)
- 用途:动态扩展对象功能(如日志、缓存)。
- Python 装饰器语法:
def log_decorator(func): def wrapper(*args, **kwargs): print(f"调用函数: {func.__name__}") return func(*args, **kwargs) return wrapper @log_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("Alice") # 输出:调用函数: say_hello → Hello, Alice!
3. 代理模式(Proxy)
- 用途:控制对象访问(如延迟加载、权限检查)。
- 示例:
class RealImage: def display(self): print("显示高清图片") class ProxyImage: def __init__(self): self._real_image = None def display(self): if self._real_image is None: self._real_image = RealImage() # 延迟加载 self._real_image.display() # 使用 proxy = ProxyImage() proxy.display() # 首次调用时加载并显示
三、行为型模式(Behavioral Patterns)
1. 观察者模式(Observer)
- 用途:实现对象间的事件通知(如消息订阅)。
- Python 实现:
class Newsletter: def __init__(self): self._subscribers = [] def subscribe(self, subscriber): self._subscribers.append(subscriber) def notify(self, message): for sub in self._subscribers: sub.update(message) class Subscriber: def update(self, message): print(f"收到消息: {message}") # 使用 news = Newsletter() news.subscribe(Subscriber()) news.notify("新文章发布!") # 输出:收到消息: 新文章发布!
2. 策略模式(Strategy)
- 用途:定义算法族并使其可互换(如排序策略切换)。
- 示例:
class PaymentStrategy: def pay(self, amount): pass class CreditCardPayment(PaymentStrategy): def pay(self, amount): print(f"信用卡支付 {amount} 元") class AlipayPayment(PaymentStrategy): def pay(self, amount): print(f"支付宝支付 {amount} 元") class PaymentContext: def __init__(self, strategy): self.strategy = strategy def execute_payment(self, amount): self.strategy.pay(amount) # 使用 context = PaymentContext(AlipayPayment()) context.execute_payment(100) # 支付宝支付 100 元
3. 状态模式(State)
- 用途:根据对象状态改变行为(如订单状态流转)。
- 示例:
class OrderState: def next_state(self): pass class PendingState(OrderState): def next_state(self): print("订单已确认 → 处理中") return ProcessingState() class ProcessingState(OrderState): def next_state(self): print("订单处理完成 → 已发货") return ShippedState() class Order: def __init__(self): self.state = PendingState() def advance(self): self.state = self.state.next_state() # 使用 order = Order() order.advance() # 订单已确认 → 处理中 order.advance() # 订单处理完成 → 已发货
四、Python 特有简化模式
1. 模块单例
- 原理:利用 Python 模块天然单例特性。
# config.py SETTINGS = {"debug": True} # main.py import config config.SETTINGS["debug"] = False # 全局唯一实例
2. 上下文管理器(Context Manager)
- 用途:资源自动管理(如文件、数据库连接)。
class DatabaseConnection: def __enter__(self): print("连接数据库") return self def __exit__(self, exc_type, exc_val, exc_tb): print("关闭连接") def query(self): print("执行查询") # 使用 with DatabaseConnection() as db: db.query() # 输出:连接数据库 → 执行查询 → 关闭连接
总结
- 优先使用Python特性:如装饰器替代复杂模式,利用动态类型减少接口约束。
- 适用场景:
- Web框架:中间件(装饰器)、路由(观察者)。
- 数据处理:工厂生成不同解析器、策略模式切换算法。
- 异步编程:状态模式管理协程状态。
- 避免过度设计:Python强调简洁,仅在复杂逻辑或扩展需求时引入模式。