Python设计模式


设计模式是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易地被他人理解、保证代码可靠性。python-patterns 则是使用 python 实现设计模式的集合。

支持的设计模式

创建型模式

抽象工厂模式(abstract_factory)

抽象工厂模式是一种软件设计模式,它提供了一种创建一系列相关或相互依赖对象的方式,而不需要指定具体类。在Python中,可以使用抽象基类(Abstract Base Class,简称ABC)和多态性来实现抽象工厂模式。

from abc import ABC, abstractmethod

class Pet(ABC):
    def __init__(self, name: str) -> None:
        self.name = name

    @abstractmethod
    def speak(self) -> None:
        pass

class Dog(Pet):
    def speak(self) -> None:
        print("woof")

class Cat(Pet):
    def speak(self) -> None:
        print("meow")

单例模式(brog)

在Python中,可以使用以下几种方式实现单例模式

  1. 使用模块级别的变量:Python的模块在程序运行期间只会被导入一次,因此可以将需要实现单例的对象作为模块级别的变量。当其他模块导入该模块时,都会引用同一个对象实例。例如:
    class OssExt:
        def __init__(self, config: dict):
            self.__oss = xxx
    
    Oss = OssExt({})
    # 使用单例对象
    from singleton import singleton_instance
  2. 使用装饰器:可以编写一个装饰器,将被装饰的类变成单例类。装饰器可以在类的实例化过程中控制返回同一个对象实例。例如:
    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 Oss:
        def __init__(self):
            # 初始化代码
    
    # 创建单例对象
    oss = Oss()
  3. 使用 __new__ 方法在创造实例时进行干预,达到实现单例模式的目的。 只适用于__init__方法不需要参数的情况。例如:
    class Oss:
        _instance = None
        def __new__(cls, *args, **kw):
            if cls._instance is None:
                cls._instance = object.__new__(cls, *args, **kw)
            return cls._instance
        def __init__(self):
            pass
    
    # 创建单例对象
    oss = Oss()
  4. 通过元类实现
    class Singleton(type):
        def __call__(cls, *args, **kwargs):
            if not hasattr(cls, '_instance'):
                cls._instance = super().__call__(*args, **kwargs)
            return cls._instance
    
    class Oss(metaclass=Singleton):
        pass
    
    oss = Oss()

建造者模式(builder)

当您需要创建一个复杂对象时,建造者模式(Builder Pattern)是一种创建型设计模式,它可以通过一系列步骤来逐步构建对象。它将对象的构造过程分离出来,使您能够根据不同的步骤和配置创建不同的对象。

以下是建造者模式的几个关键角色:

  1. 产品(Product):要构建的复杂对象。它包含了多个部分,这些部分将在建造过程中逐步创建和组装。

  2. 抽象建造者(Abstract Builder):定义了创建产品的步骤和方法。通常包含一个方法来创建产品的每个部分,以及一个方法来返回最终构建的产品。

  3. 具体建造者(Concrete Builder):实现了抽象建造者接口,并提供了构建产品的具体实现。每个具体建造者负责构建特定部分的产品。

  4. 导演(Director):负责控制建造过程的顺序和流程。它与具体建造者交互,将各个部分的构建步骤组织起来,最终产生产品。

下面是一个简单的Python代码示例,演示了建造者模式的使用:

class Product:
    def __init__(self):
        self.part_a = None
        self.part_b = None

    def __str__(self):
        return f"Part A: {self.part_a}, Part B: {self.part_b}"


class AbstractBuilder:
    def build_part_a(self):
        raise NotImplementedError

    def build_part_b(self):
        raise NotImplementedError

    def get_product(self):
        raise NotImplementedError


class ConcreteBuilder(AbstractBuilder):
    def __init__(self):
        self.product = Product()

    def build_part_a(self):
        self.product.part_a = "Part A"

    def build_part_b(self):
        self.product.part_b = "Part B"

    def get_product(self):
        return self.product


class Director:
    def __init__(self, builder):
        self.builder = builder

    def construct(self):
        self.builder.build_part_a()
        self.builder.build_part_b()


# 使用建造者模式构建产品
builder = ConcreteBuilder()
director = Director(builder)
director.construct()
product = builder.get_product()
print(product)

工厂模式(factory)

工厂模式(Factory Pattern)是一种创建对象的设计模式,它通过定义一个创建对象的接口,但具体的对象实例化的过程延迟到子类来完成。简单来说,工厂模式将对象的创建和使用分离,客户端只需要关心接口而不需要知道具体的实现细节。

在 Python 中,可以使用工厂模式来实现对象的创建。下面是一个简单的示例代码:

class Text2ImageRunner:
    params: Text2ImageParams
    stream: Optional[AbstractEventStream] = None
    node_id: str = ""
    max_concurrent_requests: int = 2

    def __init__(
        self,
        params: Text2ImageParams,
        stream: Optional[AbstractEventStream] = None,
        node_id: str = "",
    ):
        self.stream = stream
        self.params = params
        self.node_id = node_id

    @staticmethod
    def model_name(): ...

    def run(self) -> list[str]: ...

    def send_event(self, event: Event):
        if self.stream:
            self.stream.send_event(event)
class WenXinText2ImageV2(Text2ImageRunner):
    @staticmethod
    def model_name():
        return "ernie-text2image-v2"

    def run(self) -> list[str]:
        ...

class TencentText2Image(Text2ImageRunner):
    @staticmethod
    def model_name():
        return "tencent-aiart"

    def run(self) -> list[str]:
        ...

惰性评价模式(lazy_evaluation)

对象池模式(pool)

原型模式(prototype)

在Python中,原型模式可以通过使用原型设计模式来实现。原型模式是一种创建对象的设计模式,它通过复制现有对象的原型来创建新的对象,而无需显式地使用构造函数。下面是在Python中实现原型模式的一种常见方法:

import copy

class Prototype:
    def clone(self):
        return copy.deepcopy(self)


# 具体原型类
class ConcretePrototype(Prototype):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f"ConcretePrototype: {self.value}"


# 创建原型对象
prototype = ConcretePrototype("Initial")

# 克隆原型对象
clone = prototype.clone()

# 修改原型对象的值
prototype.value = "Modified"

# 打印原型和克隆对象
print(prototype)
print(clone)

# ConcretePrototype: Modified
# ConcretePrototype: Initial

结构型模式

3层模式(3-tier)

适配器模式(adapter)

桥接模式(bridge)

组合模式(composite)

装饰器模式(decorator)

装饰器模式(Decorator Pattern)是一种用于向现有对象添加额外功能的设计模式。在 Python 中,装饰器是一种特殊的函数,它可以接收一个函数作为参数,并返回一个新的函数,通常用于在不修改原始函数代码的情况下扩展其功能。
下面是一个简单的示例,演示如何使用装饰器模式:

def decorator_function(original_function):
    def wrapper_function(*args, **kwargs):
        # 在调用原始函数之前执行一些操作
        print("在调用函数之前执行一些操作")

        # 调用原始函数
        result = original_function(*args, **kwargs)

        # 在调用原始函数之后执行一些操作
        print("在调用函数之后执行一些操作")

        return result

    return wrapper_function

# 原始函数
def greet(name):
    print(f"Hello, {name}!")

# 使用装饰器
decorated_greet = decorator_function(greet)

# 调用装饰过的函数
decorated_greet("Alice")

下面是类装饰器的使用示例:

class TextTag:
    """Represents a base text tag"""

    def __init__(self, text: str) -> None:
        self._text = text

    def render(self) -> str:
        return self._text


class BoldWrapper(TextTag):
    """Wraps a tag in <b>"""

    def __init__(self, wrapped: TextTag) -> None:
        self._wrapped = wrapped

    def render(self) -> str:
        return f"<b>{self._wrapped.render()}</b>"


class ItalicWrapper(TextTag):
    """Wraps a tag in <i>"""

    def __init__(self, wrapped: TextTag) -> None:
        self._wrapped = wrapped

    def render(self) -> str:
        return f"<i>{self._wrapped.render()}</i>"


def main():
    """
    >>> simple_hello = TextTag("hello, world!")
    >>> special_hello = ItalicWrapper(BoldWrapper(simple_hello))

    >>> print("before:", simple_hello.render())
    before: hello, world!

    >>> print("after:", special_hello.render())
    after: <i><b>hello, world!</b></i>

外观模式(facade)

享元模式(flyweight)

前端控制器模式(front_controller)

MVC模式(mvc)

代理模式(proxy)

行为型模式

责任链模式(chain_of_responsibility)

目录模式(catelog)

方法链模式(chaining_method)

命令模式(command)

迭代器模式(iterator)

中介者模式(mediator)

备忘录模式(memento)

观察者模式(observer)

发布订阅模式(publish_subscribe)

注册模式(registry)

规格模式(specification)

状态模式(state)

策略模式(strategy)

模板模式(template)

访问者模式(visitor)

可测试型模式

依赖注入模式(dependency_injection)

基础模式

委托模式(delegation_pattern)

其他模式

黑板模式(blackboard)

图搜索模式(graph_search)

hsm模式(hsm)


文章作者: Wanheng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Wanheng !
评论
  目录