#具体产品对象
classMenu:
Menu_A=[]
Menu_B=[]defset_MenuA(self,item):
self.Menu_A.append(item)defset_MenuB(self,item):
self.Menu_B.append(item)defget_MenuA(self):returnself.Menu_Adefget_MenuB(self):returnself.Menu_B#Builder(抽象建造者)#创建一个Product对象的各个部件指定的抽象接口。
classProduct:
product=Menu()defbuild_hanbao(self):pass
defbuild_jiroujuan(self):pass
defbuild_kele(self):pass
defbuild_shutiao(self):pass
#ConcreteBuilder(具体建造者)#实现抽象接口,构建和装配各个部件。#套餐A
classproduct_A(Product):def __init__(self):
self.producttype="A"
defbuild_hanbao(self):
self.hanbao="汉堡"self.product.set_MenuA(self.hanbao)defbuild_kele(self):
self.kele="可乐"self.product.set_MenuA(self.kele)defgetType(self):returnself.producttype#套餐B
classproduct_B(Product):def __init__(self):
self.producttype= "B"
defbuild_shutiao(self):
self.shutiao="薯条"self.product.set_MenuB(self.shutiao)defbuild_jiroujuan(self):
self.jiroujuan="鸡肉卷"self.product.set_MenuB(self.jiroujuan)defbuild_kele(self):
self.kele="可乐"self.product.set_MenuB(self.kele)defgetType(self):returnself.producttype#Director(指挥者)
classMake:def __init__(self):
self.builder=Nonedefbuild_product(self, builder):
self.builder=builderprint(builder.producttype)if builder.producttype == "A":
[step()for step in(builder.build_hanbao,
builder.build_kele)]if builder.producttype == "B":
[step()for step in(builder.build_shutiao,
builder.build_jiroujuan,
builder.build_kele)]#不同类型选择
defvalidate_style(builders):globalvalid_inputtry:print('套餐A:汉堡、可乐'+'\n'
'套装B:薯条、鸡肉卷、可乐')
product_style= input('请输入您的选择:')
builder=builders[product_style]()
valid_input=TrueexceptKeyError as err:print('Sorry, 没有这个套餐,请重新选择。')return(False, None)return(True, builder,product_style)#主函数
defmain():
builders= dict(A=product_A, B=product_B)
valid_input=Falsewhile notvalid_input:
valid_input, builder,product_style=validate_style(builders)
Waiter=Make()
Waiter.build_product(builder)if product_style == "A":print(builder.product.get_MenuA())else:print(builder.product.get_MenuB())if __name__ =="__main__":
main()