实现Python Builder模式的不同方法
构建者模式是一种允许将对象的创建与对象的表示分离的模式。这种模式可以在没有继承的情况下创建和配置复杂的对象,这是一种强大但不灵活的方法。
构建器模式也可以用来在运行时提供一个类的不同实现,或者允许用户在不接触源代码的情况下构建新对象。
本教程介绍了构建器模式以及它们的工作原理。它还演示了实现Python构建器模式的不同方法。
构建器模式,其重要性和工作原理
构建器模式是一种软件设计模式,它允许逐步创建复杂的对象,提供一个新的细节或功能水平。
这种模式经常被用于软件开发,不同的软件组件必须被组合成一个完整的系统。
构建者模式可以用来创建任何东西,从简单的对象,如桌子或椅子,到更复杂的系统,如计算机或飞机。它也有助于创建需要按特定顺序创建的对象。
Python 标准库提供了一个叫做builder
的模块,使得使用生成器模式变得容易。构建器模块提供了两个类,Builder
和Director
,它们一起工作来创建对象。
Builder
类负责创建对象的各个部分,而Director
类则用于将各个部分组装成最终的对象。
要使用Builder
模式,你首先创建一个Builder
对象,用来创建对象的各个部分。然后你创建一个Director
对象,用来将这些部件组装成最终的对象。
最后,你可以在Director
对象上调用build()
方法,该方法返回最终对象。
在 Python 中实现生成器模式的不同方法
有两种方法可以在Python中实现Builder模式:
-
__init__
方法 -
__new__
方法
使用 __init__
方法
__init__
方法是在Python中实现Builder
模式的最常用方法。它在对象被创建时被调用,允许你设置它的属性值。
使用 __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()