跳转到内容

Python 设计模式

来自代码酷
Admin留言 | 贡献2025年4月28日 (一) 21:10的版本 (Page creation by admin bot)

(差异) ←上一版本 | 已核准修订 (差异) | 最后版本 (差异) | 下一版本→ (差异)

Python设计模式[编辑 | 编辑源代码]

设计模式是解决软件设计中常见问题的可重用方案。它们不是可以直接转换为代码的完整解决方案,而是描述如何解决特定问题的模板或蓝图。在Python中,设计模式帮助开发者编写更清晰、更可维护和更高效的代码。

简介[编辑 | 编辑源代码]

设计模式最初由“四人帮”(GoF)在《设计模式:可复用面向对象软件的基础》一书中提出,分为三大类:

  • 创建型模式:处理对象创建机制(如工厂模式、单例模式)。
  • 结构型模式:处理对象组合(如适配器模式、装饰器模式)。
  • 行为型模式:处理对象间的交互(如观察者模式、策略模式)。

Python的动态特性和简洁语法使其成为实现设计模式的理想语言。

常见设计模式及示例[编辑 | 编辑源代码]

1. 单例模式(Singleton)[编辑 | 编辑源代码]

单例模式确保一个类只有一个实例,并提供一个全局访问点。

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

# 测试
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2)  # 输出: True

应用场景:数据库连接池、日志记录器。

2. 工厂模式(Factory)[编辑 | 编辑源代码]

工厂模式通过一个公共接口创建对象,而无需指定具体类。

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class AnimalFactory:
    @staticmethod
    def create_animal(animal_type):
        if animal_type == "dog":
            return Dog()
        elif animal_type == "cat":
            return Cat()
        else:
            raise ValueError("Unknown animal type")

# 测试
dog = AnimalFactory.create_animal("dog")
print(dog.speak())  # 输出: Woof!

应用场景:动态对象创建(如插件系统)。

3. 观察者模式(Observer)[编辑 | 编辑源代码]

观察者模式定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会收到通知。

class Subject:
    def __init__(self):
        self._observers = []

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

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

class Observer:
    def update(self, message):
        print(f"Received: {message}")

# 测试
subject = Subject()
observer1 = Observer()
observer2 = Observer()
subject.attach(observer1)
subject.attach(observer2)
subject.notify("Hello!")  # 输出: Received: Hello! (两次)

应用场景:事件处理系统、GUI组件。

4. 装饰器模式(Decorator)[编辑 | 编辑源代码]

装饰器模式动态地扩展对象的功能,而无需修改其类。

class Coffee:
    def cost(self):
        return 5

class MilkDecorator:
    def __init__(self, coffee):
        self._coffee = coffee

    def cost(self):
        return self._coffee.cost() + 2

# 测试
simple_coffee = Coffee()
coffee_with_milk = MilkDecorator(simple_coffee)
print(coffee_with_milk.cost())  # 输出: 7

应用场景:日志记录、权限检查。

设计模式的选择[编辑 | 编辑源代码]

选择设计模式时需考虑:

  • 问题是否匹配模式的意图。
  • 代码可维护性与灵活性需求。
  • Python特性(如鸭子类型可能替代某些模式)。

实际案例[编辑 | 编辑源代码]

案例:电商订单系统

  • 使用工厂模式创建不同支付方式(信用卡、PayPal)。
  • 使用观察者模式通知用户订单状态变更。
  • 使用装饰器模式为订单添加折扣或税费。

classDiagram class Order { +items: List +add_item() +calculate_total() } class PaymentMethod { <<interface>> +pay(amount) } class CreditCard { +pay(amount) } class PayPal { +pay(amount) } Order --> PaymentMethod PaymentMethod <|-- CreditCard PaymentMethod <|-- PayPal

总结[编辑 | 编辑源代码]

设计模式是Python高级编程的核心工具之一。理解并合理运用它们可以显著提升代码质量。初学者应从单例、工厂等基础模式入手,逐步掌握更复杂的模式。