实现代码
from abc import ABC, abstractmethod
class Product:
def __init__(self):
self.part_a = None
self.part_b = None
self.part_c = None
def set_part_a(self, part_a):
self.part_a = part_a
def set_part_b(self, part_b):
self.part_b = part_b
def set_part_c(self, part_c):
self.part_c = part_c
def __str__(self):
return "Product(part_a=%s,part_b=%s,part_c=%s)" % (self.part_a, self.part_b, self.part_c)
class Builder(ABC):
def __init__(self):
self.product = Product()
@abstractmethod
def build_part_a(self):
...
@abstractmethod
def build_part_b(self):
...
@abstractmethod
def build_part_c(self):
...
def get_result(self):
return self.product
class ConcreteBuilder(Builder):
def build_part_a(self):
self.product.set_part_a("A")
def build_part_b(self):
self.product.set_part_b("B")
def build_part_c(self):
self.product.set_part_c("C")
class Director:
def __init__(self, builder_instance):
self.builder = builder_instance
def construct(self):
self.builder.build_part_a()
self.builder.build_part_b()
self.builder.build_part_c()
return self.builder.get_result()
if __name__ == '__main__':
builder = ConcreteBuilder()
director = Director(builder)
product = director.construct()
print(product)
链式编程风格
from abc import ABC, abstractmethod
class Builder(ABC):
def __init__(self):
self.product = Product()
@abstractmethod
def build_part_a(self):
...
@abstractmethod
def build_part_b(self):
...
@abstractmethod
def build_part_c(self):
...
def get_result(self):
return self.product
class Product:
def __init__(self):
self.part_a = None
self.part_b = None
self.part_c = None
def set_part_a(self, part_a):
self.part_a = part_a
def set_part_b(self, part_b):
self.part_b = part_b
def set_part_c(self, part_c):
self.part_c = part_c
def __str__(self):
return "Product(part_a=%s,part_b=%s,part_c=%s)" % (self.part_a, self.part_b, self.part_c)
class ConcreteBuilder(Builder):
def build_part_a(self):
self.product.set_part_a("A")
return self
def build_part_b(self):
self.product.set_part_b("B")
return self
def build_part_c(self):
self.product.set_part_c("C")
return self
if __name__ == '__main__':
builder = Product.ConcreteBuilder().build_part_a().build_part_b().build_part_c()
product = builder.get_result()
print(product)