迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

实现 Python Builder 模式的不同方法

作者:迹忆客 最近更新:2023/06/27 浏览次数:

构建器模式是一种允许对象的创建与其表示分离的模式。 这种模式可以创建和配置复杂的对象而无需继承,这是一种强大但不灵活的方法。

构建器模式还可用于在运行时提供类的不同实现,或允许用户无需访问源代码即可构造新对象。

本篇文章介绍构建器模式及其工作原理。 它还演示了实现 Python 构建器模式的不同方法。


构建器模式、它的重要性和工作原理

构建器模式是一种软件设计模式,允许逐步创建复杂对象的构造,从而提供新级别的细节或功能。

这种模式经常用于软件开发中,其中不同的软件组件必须组合起来才能形成一个完整的系统。

构建器模式可用于创建任何东西,从简单的对象(如桌子或椅子)到更复杂的系统(如计算机或飞机)。 对于创建需要按特定顺序创建的对象也很有帮助。

Python标准库提供了一个名为builder的模块,可以方便地使用Builder模式。 builder模块提供了两个类,Builder和Director,它们一起创建对象。

Builder类负责创建对象部件,Director类用于将组件组装成最终对象。

要使用 Builder 模式,首先创建一个 Builder 对象,用它来创建对象的各个部分。 然后创建一个 Director 对象,用它来将各个部分组装成最终对象。

最后,您可以调用 Director 对象的 build() 方法,该方法返回最终对象。


在 Python 中实现构建器模式的不同方法

Python 中实现 Builder 模式有两种方法:

  1. __init__ 方法
  2. __new__ 方法

使用 __init__ 方法

__init__ 方法是 Python 中实现构建器模式最常见的方法。 它在创建对象时被调用,允许您设置其属性的值。

使用 __new__ 方法

__new__ 方法不太常见,但功能更强大。 创建类时会调用 __new__ 方法,允许您创建对象本身。

这意味着您可以控制对象的创建方式,甚至可以创建与类不同类型的对象。


Python 中构建器模式的优点和缺点

下面列出了构建器模式的一些优点:

  • 构建器模式的基本优点是它允许逐步创建复杂的对象,提供新级别的细节或功能。
  • 这使得创建复杂对象变得更加简单和高效。
  • 构建器模式的另一个优点是它允许高度的灵活性,因为不同的构建器可以创建不同类型的对象。

使用构建器模式也有一些缺点。

  • 一是创建对象可能非常耗时,因为每个步骤都需要按顺序执行。
  • 另一个缺点是构建器模式可能非常复杂并且需要编写大量代码。

代码示例:

from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any

class Builder(ABC):

    @property
    @abstractmethod
    def product(self) -> None:
        pass

    @abstractmethod
    def produce_a(self) -> None:
        pass
    """
    This class will provide specific working of the building steps by using the builder interface.
    """
class ConcreteBuilder1(Builder):

    def __init__(self) -> None:
            """ This fresh builder instance will contain a blank product object, which is
        used in further assembly.
        """
            self.reset()

    def reset(self) -> None:
        self._product = Product1()

    @property
    def product(self) -> Product1:

        product = self._product
        self.reset()
        return product

    def produce_a(self) -> None:
        self._product.add("PartA")

class Product1():
    """
    When your products are complex and demand extensive configuration, it's possible to use the Builder pattern only.
    """
    def __init__(self) -> None:
        self.parts = []

    def add(self, part: Any) -> None:
        self.parts.append(part)

    def list_parts(self) -> None:
        print(f"The Product parts: {', '.join(self.parts)}", end="")

class Director:
    """
   The client can control builders directly, so the Director class is
    optional. In this case, the Director is only responsible for executing the building steps in a specific sequence.
    """
    def __init__(self) -> None:
        self._builder = None

    @property
    def builder(self) -> Builder:
        return self._builder
        """
    The Director can construct several product variations using the same
    building steps.
    """

    @builder.setter
    def builder(self, builder: Builder) -> None:
        self._builder = builder

    def build_minimal_viable_product(self) -> None:
        self.builder.produce_a()

    def build_full_featured_product(self) -> None:
        self.builder.produce_a()

if __name__ == "__main__":

    director = Director()
    builder = ConcreteBuilder1()
    director.builder = builder

    print("Our Standard primary product:")
    director.build_minimal_viable_product()
    builder.product.list_parts()

    print("\n")

    print("Our Standard full-featured product:")
    director.build_full_featured_product()
    builder.product.list_parts()

    print("\n")
 # We can also use the Builder pattern without a Director class.
    print("Our Custom product: ")
    builder.produce_a()
    builder.product.list_parts()

输出:

Our Standard primary product:
The Product parts: PartA

Our Standard full-featured product:
The Product parts: PartA

Our Custom product: 
The Product parts: PartA

请记住,构建器模式也是一种设计模式,它通过分离构造和表示来帮助构建复杂的对象。 这种分离允许通过相同的构建过程进行不同的表示。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便