Python 在开发中的设计模式有哪些?怎样使用?

大家好!我是爱摸鱼的小鸿,关注我,收看每期的编程干货。

今天我们要聊点硬核的——设计模式。不过,不用担心,我会带着热情来跟你分享这些看似枯燥的知识点。让我们一起从“代码搬砖工”蜕变成“代码艺术家”吧!

一、设计模式是什么鬼?

什么是设计模式呢?
设计模式(Design Pattern)是软件工程中,针对某一特定问题的最佳解决方案。简而言之,它是前辈们踩过无数坑后总结出的经验教训,帮助我们更优雅、更高效地写代码。

为什么需要设计模式?

  • 提高代码可读性:结构化的代码更容易理解。
  • 提升代码复用性:避免重复造轮子。
  • 增强系统扩展性:设计良好的模式使得系统更易扩展。
  • 降低维护成本:更少的bug和更简单的修改。


好了,废话不多说,接下来我们进入正题,一起来看看 Python 中的那些常用设计模式以及它们的使用方法吧!

二、创建型模式

单例模式(Singleton)
单例模式保证一个类只有一个实例,并提供一个全局访问点。这个模式在需要唯一对象的场景下非常有用,比如日志记录器、数据库连接池等。

代码示例:

class Singleton:
    _instance = None

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

# 测试单例模式
singleton1 = Singleton()
singleton2 = Singleton()

print(singleton1 is singleton2)  # True



工厂模式(Factory Method)
工厂模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。这使得类的实例化延迟到子类。

代码示例:

from abc import ABC, abstractmethod

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

class ConcreteProductA(Product):
    def operation(self):
        return "Result of ConcreteProductA"

class ConcreteProductB(Product):
    def operation(self):
        return "Result of ConcreteProductB"

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

    def some_operation(self):
        product = self.factory_method()
        return f"Creator: The same creator's code has just worked with {product.operation()}"

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

class ConcreteCreatorB(Creator):
    def factory_method(self):
        return ConcreteProductB()

# 测试工厂模式
def client_code(creator: Creator):
    print(f"Client: I'm not aware of the creator's class, but it still works.\n{creator.some_operation()}")

client_code(ConcreteCreatorA())
client_code(ConcreteCreatorB())

三、结构型模式

适配器模式(Adapter)
适配器模式允许接口不兼容的类可以一起工作。它通过包装一个对象来转换它的接口,使得原本由于接口不兼容而不能一起工作的类可以一起工作。

代码示例:

class Target:
    def request(self):
        return "Target: The default target's behavior."

class Adaptee:
    def specific_request(self):
        return ".eetpadA eht fo roivaheb laicepS"

class Adapter(Target):
    def __init__(self, adaptee: Adaptee):
        self.adaptee = adaptee

    def request(self):
        return f"Adapter: (TRANSLATED) {self.adaptee.specific_request()[::-1]}"

# 测试适配器模式
adaptee = Adaptee()
print(f"Adaptee: {adaptee.specific_request()}")

adapter = Adapter(adaptee)
print(adapter.request())



装饰器模式(Decorator)
装饰器模式通过在运行时动态地将责任附加到对象上来扩展它的功能。装饰器提供了一个灵活的替代继承的方法来扩展功能。

代码示例:

class Component:
    def operation(self):
        pass

class ConcreteComponent(Component):
    def operation(self):
        return "ConcreteComponent"

class Decorator(Component):
    def __init__(self, component: Component):
        self._component = component

    def operation(self):
        return self._component.operation()

class ConcreteDecoratorA(Decorator):
    def operation(self):
        return f"ConcreteDecoratorA({self._component.operation()})"

class ConcreteDecoratorB(Decorator):
    def operation(self):
        return f"ConcreteDecoratorB({self._component.operation()})"

# 测试装饰器模式
simple = ConcreteComponent()
print(f"Client: I've got a simple component:\n{simple.operation()}")

decorator1 = ConcreteDecoratorA(simple)
decorator2 = ConcreteDecoratorB(decorator1)
print(f"Client: Now I've got a decorated component:\n{decorator2.operation()}")

四、行为型模式

策略模式(Strategy)
策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以相互替换。策略模式让算法独立于使用它的客户而变化。

代码示例:

from abc import ABC, abstractmethod

class Strategy(ABC):
    @abstractmethod
    def do_algorithm(self, data: list):
        pass

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

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

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

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

    def do_some_business_logic(self):
        print("Context: Sorting data using the strategy")
        result = self._strategy.do_algorithm(["a", "b", "c", "d", "e"])
        print(",".join(result))

# 测试策略模式
context = Context(ConcreteStrategyA())
print("Client: Strategy is set to normal sorting.")
context.do_some_business_logic()

print("\nClient: Strategy is set to reverse sorting.")
context.set_strategy(ConcreteStrategyB())
context.do_some_business_logic()



观察者模式(Observer)
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。当主题对象状态发生变化时,它会通知所有观察者对象,使它们能够自动更新自己。

代码示例:

class Subject:
    _state: int = None
    _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)

    def some_business_logic(self):
        self._state = 123
        self.notify()

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

class ConcreteObserverA(Observer):
    def update(self, subject):
        if subject._state == 123:
            print("ConcreteObserverA: Reacted to the event")

class ConcreteObserverB(Observer):
    def update(self, subject):
        if subject._state == 123:
            print("ConcreteObserverB: Reacted to the event")

# 测试观察者模式
subject = Subject()

observer1 = ConcreteObserverA()
subject.attach(observer1)

observer2 = ConcreteObserverB()
subject.attach(observer2)

subject.some_business_logic()

五、结语

今天我们一起探索了几种常见的设计模式,并且提供了相应的 Python 代码示例。设计模式不仅仅是代码的优化手段,更是一种编程思想的升华。希望你能从中学到一些新的知识,并在实际项目中灵活应用这些设计模式,写出更加优雅、高效的代码。

记住,编程不仅仅是一种技能,更是一门艺术。愿你在编程的道路上不断前行,成为一个真正的“代码艺术家”!

在这里插入图片描述

六、作者Info

Author:小鸿的摸鱼日常

Goal:让编程更有趣! 专注于 Web 开发、爬虫,游戏开发,数据分析、自然语言处理,AI 等,期待你的关注,让我们一起成长、一起 Coding!

版权说明:本文禁止抄袭、转载,侵权必究!

  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鸿的摸鱼日常

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值