程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 设计模式:初学者指南(python做设计)

hfteth 2025-04-09 16:22:38 技术文章 17 ℃

设计模式是软件设计中常见问题的可重用解决方案。它们提供了一个模板,用于以一种经过验证、高效和广泛理解的方式解决问题。Python 具有简单性和可读性,是学习和实现设计模式的优秀语言。。

创建式设计模式

创建模式侧重于对象的创建方式,确保代码的灵活性和重用性。让我们来探讨一下这个类别中的几个关键模式。

单例模式

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

用例:管理共享资源,如数据库连接或日志记录服务。

实际应用:Python 的内置日志记录模块实现了 Singleton 模式,以确保应用程序的所有部分共享同一个 Logger 实例。

实现:

class Singleton:
    _instance = None

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

# Test Singleton
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2)  # Output: True

常见陷阱:单例可能会在多线程应用程序中引入问题。使用线程安全机制,如线程。锁定以避免争用条件。

Factory Method 模式

Factory Method 模式提供了一个在超类中创建对象的接口,但允许子类更改将要创建的对象的类型。

用例:创建对象而不指定要实例化的确切类。

实际应用:Python 的 tkinter 库使用工厂方法创建按钮和标签等 UI 元素。

实现:

class Shape:
    def draw(self):
        raise NotImplementedError

class Circle(Shape):
    def draw(self):
        return "Drawing a Circle"

class Square(Shape):
    def draw(self):
        return "Drawing a Square"

class ShapeFactory:
    @staticmethod
    def get_shape(shape_type):
        if shape_type == "Circle":
            return Circle()
        elif shape_type == "Square":
            return Square()
        else:
            return None

# Usage
shape = ShapeFactory.get_shape("Circle")
print(shape.draw())  # Output: Drawing a Circle

结构设计模式

结构模式处理类或对象的组合以形成更大的结构。

适配器模式

Adapter 模式通过在不兼容的接口之间创建桥接来允许它们一起工作。

用例:将第三方库集成到您的应用程序中。

实际应用:调整具有不兼容 API 的库以使用现有代码库。

实现:

class EuropeanPlug:
    def connect(self):
        return "Connected with European plug"

class Adapter:
    def __init__(self, european_plug):
        self.european_plug = european_plug

    def connect(self):
        return self.european_plug.connect() + " using an adapter"

# Usage
european_plug = EuropeanPlug()
adapter = Adapter(european_plug)
print(adapter.connect())  # Output: Connected with European plug using an adapter

装饰器图案

Decorator 模式动态地向对象添加行为或职责,而无需修改其结构。

用例:向函数或方法添加其他功能。

实际应用:Python 的 functools 模块支持像 @lru_cache 这样的装饰器来缓存函数结果。

实现:

from functools import wraps

def bold(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"{func(*args, **kwargs)}"
    return wrapper

@bold
def greet():
    return "Hello, World!"

print(greet())  # Output: Hello, World!

常见陷阱:忘记使用 functools.wraps 可能会导致元数据丢失,例如原始函数名称和文档字符串。

行为设计模式

行为模式侧重于对象之间的通信。

观察者模式

Observer 模式定义了一对多的依赖关系,这样当一个对象更改状态时,其所有依赖关系都会得到通知。

用例:实现事件系统或发布-订阅模型。

实际应用:GUI 框架通常使用 Observer 模式来管理 UI 事件处理。

实现:

class Observer:
    def update(self, message):
        raise NotImplementedError

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

class Publisher:
    def __init__(self):
        self.subscribers = []

    def subscribe(self, observer):
        self.subscribers.append(observer)

    def unsubscribe(self, observer):
        self.subscribers.remove(observer)

    def notify(self, message):
        for subscriber in self.subscribers:
            subscriber.update(message)

# Usage
publisher = Publisher()
subscriber1 = Subscriber()
subscriber2 = Subscriber()

publisher.subscribe(subscriber1)
publisher.subscribe(subscriber2)

publisher.notify("New event available!")  # Output: Received: New event available!

策略模式

Strategy 模式允许通过将不同的算法封装为单独的类,在运行时选择类的行为。

用例:动态更改对象的行为。

实际应用:机器学习模型通常使用此模式根据输入数据应用不同的预处理策略。

实现:

class Strategy:
    def execute(self, data):
        raise NotImplementedError

class ConcreteStrategyA(Strategy):
    def execute(self, data):
        return sorted(data)

class ConcreteStrategyB(Strategy):
    def execute(self, data):
        return sorted(data, reverse=True)

class Context:
    def __init__(self, strategy):
        self.strategy = strategy

    def set_strategy(self, strategy):
        self.strategy = strategy

    def execute_strategy(self, data):
        return self.strategy.execute(data)

# Usage
data = [5, 3, 1, 4, 2]
context = Context(ConcreteStrategyA())
print(context.execute_strategy(data))  # Output: [1, 2, 3, 4, 5]

context.set_strategy(ConcreteStrategyB())
print(context.execute_strategy(data))  # Output: [5, 4, 3, 2, 1]

常见陷阱和何时不使用模式

  1. 过度复杂化:将模式应用于简单问题可能会使代码变得不必要地复杂。
  2. 过早优化:仅当模式解决应用程序中实际的、反复出现的问题时,才使用模式。

更广泛的背景

  • SOLID 原则:许多设计模式与 SOLID 原则一致,例如开/闭原则(例如,策略模式)。
  • 架构模式:设计模式通常是 MVC 或微服务等大型架构的构建块。

Tags:

最近发表
标签列表