【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"
相关推荐
只待花开2 小时前
QT5.12.9 通过MinGW64 / MinGW32 cmake编译Opencv4.5.1
开发语言·qt
我写代码菜如坤2 小时前
C#中Stopwatch的使用
开发语言·c#
wjs20243 小时前
SQLite Glob 子句
开发语言
aliceDingYM4 小时前
Linux python3.6安装mayavi报错
linux·python·ui
MarkHD6 小时前
javascript 常见设计模式
开发语言·javascript·设计模式
海盗猫鸥6 小时前
C++入门基础篇(1)
开发语言·c++·学习
专注成就自我7 小时前
java使用easypoi模版导出word详细步骤
java·开发语言·word
.生产的驴7 小时前
SpringBoot AOP切入点表达式
spring boot·后端·python
多多*7 小时前
SpringBoot 启动流程六
java·开发语言·spring boot·后端·spring
让你三行代码QAQ7 小时前
SpringSecurity初始化过程
java·开发语言