python设计模式-建造者模式
问题:在上一篇python设计模式:抽象工厂模式中,我们尝试用抽象工厂模式规范化了 Pizza 原材料的供应以及 Pizza 的创建。但是我们忽略了一个问题,那就是每种 Pizza 的烘焙时间依赖于生面团的厚度和使用的配料,它们所需的时间是不一样的。那这时我们改如何处理呢? Pizza 的制作流程包括:准备(擀面皮、加佐料),然后烘烤、切片、装盒。这些有特定的顺序,不能错乱。 为了保证 生产 Pizza 的步骤不会出错,我们打算指派一个创建者,创建者用于控制 Pizza 的制作流程。 创建 Pizza 创建者 首先我们定义一个 Pizza class Pizza: def __init__(self, name): self.name = name self.dough = None self.sauce = None self.toppings = [] def prepare_dough(self, dough): self.dough = dough print(self.dough) print('preparing the {} dough of your {}...'.format(self.dough, self)) time.sleep(STEP_DELAY) print('Done with the {} dough'.format(self.dough)) def __str__(self): return self.name 然后我们抽象出一个创建者: class PizzaBuilder(object): name = None def __init__(self): self.progress = PIZZA_PROGRESS self.baking_time = 5 def prepare_dough(self): raise NotImplementedError() def add_sauce(self): raise NotImplementedError() def add_topping(self): raise NotImplementedError() def bake(self): raise NotImplementedError() def cut(self): raise NotImplementedError() def box(self): raise NotImplementedError() @property def pizza(self): return Pizza(self.name) 创建具体建造者 class NYStyleCheeseBuilder(PizzaBuilder): name = 'NY Style Sauce and Cheese Pizza' def prepare_dough(self): self.progress = PIZZA_PROGRESS[0] self.pizza.prepare_dough('thin') def add_sauce(self): print('adding the tomato sauce to your pizza..') self.pizza.sauce = 'tomato' time.sleep(STEP_DELAY) print('done with the tomato sauce') def add_topping(self): print('adding the topping (grated reggiano cheese) to your pizza') self.pizza.toppings.append(["Grated", "Reggiano", "Cheese"]) time.sleep(STEP_DELAY) print('done with the topping (grated reggiano cheese)') def bake(self): self.progress = PIZZA_PROGRESS[1] print('baking your pizza for {} seconds'.format(self.baking_time)) time.sleep(self.baking_time) def cut(self): self.progress = PIZZA_PROGRESS[2] print("Cutting the pizza into diagonal slices") def box(self): self.progress = PIZZA_PROGRESS[3] print("Place pizza in official PizzaStore box") 创建指挥者 class Waiter: # 指挥者 def __init__(self): self.builder = None def construct_pizza(self, builder): self.builder = builder # 一旦我们有了一个 pizza,需要做一些准备(擀面皮、加佐料),然后烘烤、切片、装盒 [step() for step in (builder.prepare_dough, builder.add_sauce, builder.add_topping, builder.bake, builder.cut, builder.box)] @property def pizza(self): return self.builder.pizza 完整代码参考:python-design-patter-builder ...