Introduction and usage of Python builder mode

1. Introduction to Python builder mode

        1. Concept

Builder pattern (Builder Pattern) is a creational design pattern, which can separate the construction and representation of complex objects, so that the same construction process can create different representations. This pattern creates complex objects step by step, decoupling the object construction process from the representation process.

        2. Function

The builder pattern makes the construction process of the object independent of its representation, and can flexibly combine different construction processes to obtain different representations.

        3. Advantages

  • Decoupling the construction process of an object from its representation can flexibly combine different construction processes to obtain different representations.
  • Make the code structure more clear, easy to maintain and expand.
  • It can effectively control the object creation process and generate objects that meet the design requirements.

        5. Disadvantages

  • The builder pattern requires writing more code, and requires a certain amount of time and effort when constructing objects.
  • If fewer objects need to be created or if the structure is simpler, the builder pattern may increase the complexity of the code.

        6. Application scenarios

The builder pattern is usually used in the following scenarios:

  • Complex objects need to be created.
  • A series of related objects need to be created, and their construction process is roughly the same.
  • Some control over the construction of objects is required to ensure that the resulting objects conform to the design requirements.

        7. How to use

In Python, the builder pattern can be implemented using classes and methods. Generally speaking, the builder pattern includes the following components:

  • Product class (Product): Represents the complex object being constructed.
  • Abstract builder class (Builder): Declare abstract methods to build different parts of complex objects.
  • Concrete Builder class (Concrete Builder): Implement the methods in the abstract builder class to build various parts of the object and return the constructed object.
  • Director class (Director): Responsible for calling methods in specific builder classes to build complex objects.

        8. Application in Application Development

The builder pattern has a wide range of application scenarios in application development. For example, in Web development, we can use the builder pattern to build complex HTML pages, mail messages, etc. In game development, we can use the builder mode to generate game scenes, characters, etc. In database development, we can use the builder mode to build SQL query statements and so on.

2. Example of builder mode

working principle

The working principle of the Python builder mode mainly involves the following roles and steps:

  1. Product class (Product): Represents the complex object being constructed.

  2. Abstract builder class (Builder): Declare abstract methods to build different parts of complex objects.

  3. Concrete Builder class (Concrete Builder): Implement the methods in the abstract builder class to build various parts of the object and return the constructed object.

  4. Director class (Director): Responsible for calling methods in specific builder classes to build complex objects.

The specific workflow is as follows:

  1. Create a product class that represents the complex object to be built, which can contain multiple parts.

  2. Create an abstract builder class that declares abstract methods to build the different parts.

  3. Create a concrete builder class that implements the methods in the abstract builder class, builds parts of the object, and returns the built object.

  4. Create a conductor class that is responsible for calling methods in concrete builder classes to build complex objects.

  5. In the application, create an instance of the concrete builder class and pass it to the director class. The conductor class uses the methods in the concrete builder class to build complex objects.

  6. Finally, the constructed complex object can be used by the application.

The working principle of the Python builder mode can be simplified as follows: by separating the construction process of complex objects from the representation, and flexibly combining different construction processes to obtain different representations. Its core is to construct objects step by step, so that the construction process and performance of the object are independent of each other, and at the same time, different forms of expression can be obtained by changing some parts of the construction process.

example

Suppose we need to build a computer, which includes CPU, memory, hard disk, graphics card and other components. We can use the Python builder pattern to construct this complex object. The specific implementation steps are as follows:

  1. First, create a product category—computer category, which includes components such as CPU, memory, hard disk, and graphics card, and provides methods for setting and obtaining each component.
  2. Then create an abstract builder class - the computer builder class, which declares the abstract methods for building the different parts:
  3. Then create concrete builder classes—the desktop builder class and the notebook builder class, which implement the methods in the abstract builder class, build each part of the object, and return the built object:
  4. Due to the complexity of the computer construction process, we need to create a commander class - the computer assembler class, which is responsible for calling the methods in the specific builder class to build complex objects:
  5. Finally, we can use the above code to create different computers, for example:

# 创建产品类
class Computer():
    def __init__(self):
        self.cpu = None
        self.memory = None
        self.hark_disk = None
        self.graphics_card = None

    def set_cpu(self, cpu):
        self.cpu = cpu
    def set_memory(self, memory):
        self.memory = memory
    def set_hard_disk(self, hard_disk):
        self.hark_disk = hard_disk
    def set_graphics_card(self, graphics_card):
        self.graphics_card = graphics_card
    def get_specs(self):
        specs = f'CPU:{self.cpu}\nMemory:{self.memory}\nHard Disk:{self.hark_disk}\nGraphics Card:{self.graphics_card}'
        return specs

# 创建抽象的建造者类
class ComputerBuilder():
    def build_cpu(self): # 声明构建不同部分的抽象方法
        pass
    def build_memory(self):
        pass
    def build_hard_disk(self):
        pass
    def build_graphics_card(self):
        pass
    def get_computer(self):
        pass

# 创建具体的建造者类
class DesktopBuilder(ComputerBuilder): # 继承抽象的建造者类
    def __init__(self):
        self.computer = Computer() # 初始化产品类
    def build_cpu(self): # 实现抽象建造者方法
        self.computer.set_cpu("Intel Core 7") # 设置产品类方法值
    def build_memory(self):
        self.computer.set_memory("16GB DDR4")
    def build_hard_disk(self):
        self.computer.set_hard_disk("1TB HDD")
    def build_graphics_card(self):
        self.computer.set_graphics_card("NVIDIA GTX 1050")
    def get_computer(self):
        return self.computer

class LaptopBuilder(ComputerBuilder):
    def __init__(self):
        self.computer = Computer()
    def build_cpu(self):
        self.computer.set_cpu("Intel Core i5")
    def build_memory(self):
        self.computer.set_memory("8GB DDR4")
    def build_hard_disk(self):
        self.computer.set_hard_disk("256GB SSD")
    def build_graphics_card(self):
        self.computer.set_graphics_card("Intergrated")
    def get_computer(self):
        return self.computer
# 创建指挥者
class ComputerAssembler:
    def __init__(self,builder):
        self.builder = builder
    def assemble(self):
        self.builder.build_cpu() # 调用具体建造者类方法
        self.builder.build_memory()
        self.builder.build_hard_disk()
        self.builder.build_graphics_card()
        return self.builder.get_computer()
# 创建台式计算机
desktop_builder = DesktopBuilder()
desktop_assembler = ComputerAssembler(desktop_builder)
desktop = desktop_assembler.assemble()
print(desktop.get_specs())

# 创建笔记本计算机
laptop_builder = LaptopBuilder()
laptop_assembler = ComputerAssembler(laptop_builder)
laptop = laptop_assembler.assemble()
print(laptop.get_specs())


The output is as follows:

CPU:Intel Core 7
Memory:16GB DDR4
Hard Disk:1TB HDD
Graphics Card:NVIDIA GTX 1050
CPU:Intel Core i5
Memory:8GB DDR4
Hard Disk:256GB SSD
Graphics Card:Intergrated

Through the above examples, we can see how to use the Python builder mode. It constructs objects step by step, making the construction process and performance of objects independent of each other, and also provides better flexibility and maintainability.

おすすめ

転載: blog.csdn.net/songpeiying/article/details/131902497