Python 设计模式

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+)。

  1. 单例模式 (Singleton)
    确保一个类只有一个实例,常用于数据库连接、日志器等。
   class Singleton:
       _instance = None

       def __new__(cls, *args, **kwargs):
           if cls._instance is None:
               cls._instance = super().__new__(cls)
           return cls._instance

   # 使用
   s1 = Singleton()
   s2 = Singleton()
   print(s1 is s2)  # True
  1. 工厂方法 (Factory Method)
    定义创建接口,让子类决定实例化哪个类。
   from abc import ABC, abstractmethod

   class Product(ABC):
       @abstractmethod
       def operation(self):
           pass

   class ConcreteProductA(Product):
       def operation(self):
           return "Product A"

   class ConcreteProductB(Product):
       def operation(self):
           return "Product B"

   class Creator(ABC):
       @abstractmethod
       def factory_method(self):
           pass

       def some_operation(self):
           product = self.factory_method()
           return f"Creator: {product.operation()}"

   class ConcreteCreatorA(Creator):
       def factory_method(self):
           return ConcreteProductA()

   # 使用
   creator = ConcreteCreatorA()
   print(creator.some_operation())  # Creator: Product A
  1. 观察者模式 (Observer)
    一对多依赖,当主体变化时通知观察者(常用于事件系统)。
   class Subject:
       def __init__(self):
           self._observers = []

       def attach(self, observer):
           self._observers.append(observer)

       def notify(self):
           for observer in self._observers:
               observer.update(self)

   class Observer:
       def update(self, subject):
           print(f"Observer notified: {subject}")

   # 使用
   subject = Subject()
   observer = Observer()
   subject.attach(observer)
   subject.notify()  # Observer notified: <__main__.Subject object at ...>
  1. 装饰器模式 (Decorator)
    动态添加职责(Python 有内置 @decorator 语法)。
   def decorator(func):
       def wrapper(*args, **kwargs):
           print("Before call")
           result = func(*args, **kwargs)
           print("After call")
           return result
       return wrapper

   @decorator
   def greet(name):
       return f"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 示例。

如果需要某个具体模式的详细解释、更多代码或应用场景,请告诉我!

文章已创建 3511

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部