返回

学Python,掌握设计模式解锁高效编程新境界

后端

揭开 Python 设计模式的奥秘:解锁高效编程的 23 种创意

在编程领域,设计模式就像是一组久经考验的工具,它们可以帮助你解决常见的编程难题,提升代码的可重用性和可维护性。掌握设计模式不仅能让你编写出更简洁易读的代码,还能让你在面对复杂问题时游刃有余。

Python 是一门强大的编程语言,拥有丰富的设计模式,本文将深入探讨其中 23 种经典的设计模式,并通过 Python 代码示例进行演示,助力你快速掌握这些模式,提升编程技能。

工厂模式:对象创建的灵活掌控

工厂模式将对象的创建过程封装起来,让你无需指定具体类就能创建对象。这种模式便于系统扩展,你可以轻松添加或删除新的类。

示例代码:

class CarFactory:
    def create_car(self, car_type):
        if car_type == "Sedan":
            return Sedan()
        elif car_type == "SUV":
            return SUV()
        else:
            raise ValueError("Invalid car type")

class Sedan:
    pass

class SUV:
    pass

car_factory = CarFactory()
sedan = car_factory.create_car("Sedan")
suv = car_factory.create_car("SUV")

抽象工厂模式:相关对象的统一创建

抽象工厂模式提供了一个接口,用于创建一组相关对象,而无需指定它们的具体类。这种模式让你可以轻松创建一系列相关的对象,无需了解它们的具体细节。

示例代码:

class ShapeFactory:
    def create_shape(self, shape_type):
        if shape_type == "Circle":
            return Circle()
        elif shape_type == "Square":
            return Square()
        else:
            raise ValueError("Invalid shape type")

class Circle:
    pass

class Square:
    pass

shape_factory = ShapeFactory()
circle = shape_factory.create_shape("Circle")
square = shape_factory.create_shape("Square")

建造者模式:复杂对象的逐步构建

建造者模式将复杂对象的构建过程分解成一系列独立的步骤,让你可以一步一步地创建对象。这种模式可以让你轻松创建复杂的对象,而无需担心构建过程的细节。

示例代码:

class PizzaBuilder:
    def __init__(self):
        self.pizza = Pizza()

    def add_toppings(self, toppings):
        self.pizza.toppings.extend(toppings)

    def set_size(self, size):
        self.pizza.size = size

    def get_pizza(self):
        return self.pizza

class Pizza:
    def __init__(self):
        self.size = ""
        self.toppings = []

pizza_builder = PizzaBuilder()
pizza_builder.set_size("Large")
pizza_builder.add_toppings(["pepperoni", "sausage"])
pizza = pizza_builder.get_pizza()

单例模式:唯一实例的保障

单例模式确保一个类只有一个实例,并提供一个全局访问点。这种模式让你可以轻松地共享对象,而无需担心创建多个实例。

示例代码:

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

singleton1 = Singleton()
singleton2 = Singleton()

print(singleton1 is singleton2)  # True

适配器模式:兼容性的桥梁

适配器模式将一个类的接口转换成另一个类所期望的接口,从而使两个不兼容的类可以一起工作。这种模式可以让你轻松地整合不同的系统和组件。

示例代码:

class OldSystemInterface:
    def get_data(self):
        return "Old data"

class NewSystemInterface:
    def get_data(self):
        return {"new_data": "New data"}

class Adapter(OldSystemInterface):
    def __init__(self, new_system):
        self.new_system = new_system

    def get_data(self):
        return self.new_system.get_data()

old_system = OldSystemInterface()
new_system = NewSystemInterface()
adapter = Adapter(new_system)

print(old_system.get_data())  # Old data
print(adapter.get_data())  # {"new_data": "New data"}

代理模式:替身与控制

代理模式为另一个对象提供一个替代或占位符,以便控制对该对象的访问。这种模式可以让你轻松地添加额外的功能或控制对对象的访问。

示例代码:

class RealSubject:
    def operation(self):
        print("RealSubject operation")

class Proxy:
    def __init__(self, real_subject):
        self.real_subject = real_subject

    def operation(self):
        print("Proxy operation")
        self.real_subject.operation()

real_subject = RealSubject()
proxy = Proxy(real_subject)

proxy.operation()  # Proxy operation
# RealSubject operation

装饰器模式:动态扩展

装饰器模式动态地将额外的功能添加到一个对象,而无需修改该对象本身。这种模式可以让你轻松地扩展对象的 functionality。

示例代码:

def add_logging(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args {args} and kwargs {kwargs}")
        result = func(*args, **kwargs)
        print(f"Called {func.__name__} with args {args} and kwargs {kwargs}")
        return result
    return wrapper

@add_logging
def my_function(a, b):
    return a + b

my_function(1, 2)  # Calling my_function with args (1, 2) and kwargs {}
# Called my_function with args (1, 2) and kwargs {}
# 3

策略模式:算法的多样性

策略模式将一个算法封装起来,以便你可以随时改变算法,而无需修改客户端代码。这种模式可以让你轻松地实现算法的可重用性和可维护性。

示例代码:

class Strategy:
    def execute(self):
        pass

class ConcreteStrategyA(Strategy):
    def execute(self):
        print("Strategy A executed")

class ConcreteStrategyB(Strategy):
    def execute(self):
        print("Strategy B executed")

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

    def execute_strategy(self):
        self.strategy.execute()

context = Context(ConcreteStrategyA())
context.execute_strategy()  # Strategy A executed

context.strategy = ConcreteStrategyB()
context.execute_strategy()  # Strategy B executed

观察者模式:事件与通知

观察者模式定义了一种对象之间的一对多依赖关系,以便当一个对象的状态发生改变时,所有依赖它的对象都会得到通知。这种模式可以让你轻松地实现对象之间的通信。

示例代码:

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

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

    def detach(self, observer):
        self._observers.remove(observer)

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

class Observer:
    def update(self, subject):
        pass

class ConcreteObserverA(Observer):
    def update(self, subject):
        print("Observer A notified")

class ConcreteObserverB(Observer):
    def update(self, subject):
        print("Observer B notified")

subject = Subject()
observer_a = ConcreteObserverA()
observer_b = ConcreteObserverB()

subject.attach(observer_a)
subject.attach(observer_b)

subject.notify()  # Observer A notified
# Observer B notified

发布-订阅模式:消息分发

发布-订阅模式定义了一种发布者-订阅者模型,其中发布者可以将消息发送给多个订阅者,而订阅者可以根据自己的需要选择是否接收消息。这种模式可以让你轻松地实现事件驱动的系统。

示例代码:

import pubsub

class Publisher:
    def __init__(self):
        self.pubsub = pubsub.PubSub()

    def publish(self, topic, data):
        self.pubsub.publish(topic, data)

class Subscriber:
    def __init__(self, topic):
        self.pubsub = pubsub.PubSub()
        self.pubsub.subscribe(topic, self.on_message)

    def on_message(self, topic,