【Python进阶编程】python编程高手常用的设计模式(持续更新中)

Python编程高手通常熟练运用各种设计模式,这些设计模式有助于提高代码的可维护性、可扩展性和重用性。

以下是一些Python编程高手常用的设计模式:

1.单例模式(Singleton Pattern)

确保一个类只有一个实例,并提供全局访问点。适用于需要共享资源或控制特定资源访问的情景。

python 复制代码
class Singleton(object):
    _instance = None

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


s1 = Singleton()
s2 = Singleton()
print(id(s1))
print(id(s2)) # s1和s2的ID应该是一样的,表明这是同一个对象

其他实现单例模式的方法。

1.1 使用模块级别的变量实现单例模式

python 复制代码
# singleton_module.py

class Singleton:
    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value

singleton_instance = Singleton()

Python模块在程序中只会被导入一次,因此模块级别的变量可以实现单例模式。

在其他文件中,可以通过导入singleton_module模块来获取单例对象:

python 复制代码
# main.py

from singleton_module import singleton_instance

# 使用单例对象
singleton_instance.set_value(42)
print(singleton_instance.get_value())

1.2 使用类装饰器实现单例模式

可以使用装饰器来确保类只有一个实例,并通过装饰器在需要时创建实例。

python 复制代码
# singleton_decorator.py

def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class Singleton:
    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value

在这种方式下,可以直接使用@singleton装饰器标记一个类为单例,然后通过类的实例获取单例对象:

python 复制代码
# main.py

from singleton_decorator import Singleton

# 使用单例对象
singleton_instance = Singleton()
singleton_instance.set_value(42)
print(singleton_instance.get_value())

2. 工厂模式(Factory Pattern)

  1. 定义一个接口,但由子类决定实例化哪个类。工厂方法模式将类的实例化延迟到子类。

    python 复制代码
    class Product(ABC):
        @abstractmethod
        def create_product(self):
            pass
    
    class ConcreteProductA(Product):
        def create_product(self):
            return "Product A"
    
    class ConcreteProductB(Product):
        def create_product(self):
            return "Product B"

    3.观察者模式(Observer Pattern)

python 复制代码
from abc import ABC, abstractmethod

class Observer(ABC):
    @abstractmethod
    def update(self, message):
        pass

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

class Subject:
    _observers = []

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

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

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

​​​​​​4. 策略模式(Strategy Pattern)

  1. 定义一系列算法,将每个算法封装起来,并使它们可以互换。策略模式可以使算法独立于客户端而变化。

    python 复制代码
    from abc import ABC, abstractmethod
    
    class Strategy(ABC):
        @abstractmethod
        def execute(self):
            pass
    
    class ConcreteStrategyA(Strategy):
        def execute(self):
            return "Strategy A"
    
    class ConcreteStrategyB(Strategy):
        def execute(self):
            return "Strategy B"
    
    class Context:
        def __init__(self, strategy):
            self._strategy = strategy
    
        def execute_strategy(self):
            return self._strategy.execute()

5.装饰器模式(Decorator Pattern)

  1. 动态地给一个对象添加一些额外的职责,装饰模式比继承更加灵活。

    复制代码
    python 复制代码
    from abc import ABC, abstractmethod
    
    class Component(ABC):
        @abstractmethod
        def operation(self):
            pass
    
    class ConcreteComponent(Component):
        def operation(self):
            return "Concrete Component"
    
    class Decorator(Component):
        _component = None
    
        def __init__(self, component):
            self._component = component
    
        def operation(self):
            return self._component.operation()
    
    class ConcreteDecorator(Decorator):
        def operation(self):
            return f"{super().operation()}, Decorated"
相关推荐
小叶肥辉5 小时前
LangChain链和LangGraph图的学习笔记【六】——提示语模板(3)——Few-Shot Prompting(少样本提示) 模板类
笔记·python·学习·langchain·prompt·aigc
for_ever_love__6 小时前
爬虫项目: 获取高分电影的数据总结
开发语言·python·学习
文人sec6 小时前
MYSQL:insert...select:为什么锁源表的所有行和间隙?怎么最快地复制一张表?
数据库·python·mysql
weixin_307779136 小时前
C++代码实现MATLAB中的ode23t函数功能
开发语言·c++·算法·matlab
SamChan906 小时前
PyMuPDF vs pdfplumber vs pypdf:PDF 文本提取实测对比(翻译预处理视角)
python·ai·pdf
君顾16 小时前
24小时自助健身房系统开发实战与完整指南
java·开发语言·健身房
辰辉创聚6 小时前
炎症与免疫相关细胞因子:信号通路、分类及科研检测应用
python·oracle·nycodenz·重组il-6蛋白·抗tnf-α抗体·il-1β蛋白
ai小陈6 小时前
LTX2.5音视频生成任务验收实战:批量记录与音画质量检查
人工智能·python·深度学习·ai·音视频·gpu算力
今儿敲了吗6 小时前
04英文文本关键词提取(TF-IDF)
笔记·python
syagain_zsx6 小时前
算法基础篇 · 02 高精度(C++ 题解)
开发语言·c++·学习·高精度