# 建造者

```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/10/7 8:02 PM
# @Author  : xinfa.jiang
# @Site    : 
# @File    : builder.py
# @Software: PyCharm
'''
建造者模式
将一个复杂对象的构建与它的表示分离, 使得同样的构建过程可以创建不同的表示
'''
from abc import ABCMeta, abstractmethod


class Product(object):
    """
    具体产品
    """

    def __init__(self):
        self.__parts = []

    def add(self, part):
        self.__parts.append(part)

    def show(self):
        print('-'.join(self.__parts))


class Builder(object):
    """
    为创建一个product对象的各个部件指定的抽象接口
    """

    __metaclass__ = ABCMeta

    @abstractmethod
    def build_part_1(self):
        pass

    @abstractmethod
    def build_part_2(self):
        pass

    @abstractmethod
    def get_result(self):
        pass


class BuilderA(Builder):
    """
    具体建造者A
    """

    def __init__(self):
        self.__product = Product()

    def build_part_1(self):
        self.__product.add("partA1")

    def build_part_2(self):
        self.__product.add("partA2")

    def get_result(self):
        return self.__product


class BuilderB(Builder):
    """
    具体建造者B
    """

    def __init__(self):
        self.__product = Product()

    def build_part_1(self):
        self.__product.add("partB1")

    def build_part_2(self):
        self.__product.add("partB2")

    def get_result(self):
        return self.__product


class Director(object):
    """
    指挥构建过程
    director不知道自己用的是哪个, 即: 只有不知道, 才能随时替换
    """

    @staticmethod
    def construct(builder):
        builder.build_part_1()
        builder.build_part_2()


if __name__ == '__main__':
    ba = BuilderA()
    bb = BuilderB()

    Director.construct(ba)
    product = ba.get_result()
    product.show()

    Director.construct(bb)
    product = bb.get_result()
    product.show()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/pattern/builder.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
