Python
設計模式
建造者模式
範例一
class Product:
def __init__(self):
self.name=''
self.parameter1 = ''
self.parameter2 = ''
self.parameter3 = ''
class Builder:
def __init__(self):
self.product = None
def SetName(self):
pass
def SetParameter1(self):
pass
def SetParameter2(self):
pass
def SetParameter3(self):
pass
class Product1Builder(Builder):
def SetName(self):
self.product.name = 'Product1'
def SetParameter(self):
self.product.parameter1 = '1-1'
def SetParameter(self):
self.product.parameter2 = '1-2'
def SetParameter(self):
self.product.parameter3 = '1-3'
class Direct:
def __init__(self):
self.productBuilder = None
def Build(self):
if self.productBuilder != None:
return self.productBuilder.BuildProduct()
else:
return None
def SetBuilder(self, builder):
self.productBuilder = builder
def
BuildProduct(self): self.productBuilder.product = Product()
self.productBuiilder.SetName()
self.productBuilder.SetParameter1()
self.productBuilder.SetParameter2()
self.productBuilder.SetParameter3()
return self.product
d = Direct()
d.SetBuilder(Product1Builder())
P1 = d.Build()
P2 = d.Build()
print(P1 == P2)
print(id(P1), id(P2))
範例二
class Product:
def __init__(self):
self.name=''
self.parameter1 = ''
self.parameter2 = ''
self.parameter3 = ''
class Builder:
def __init__(self):
self.product = None
def SetName(self):
pass
def SetParameter1(self):
pass
def SetParameter2(self):
pass
def SetParameter3(self):
pass
def BuildProduct(self):
pass
class Product1Builder(Builder):
def SetName(self):
self.product.name = 'Product1'
def SetParameter(self):
self.product.parameter1 = '1-1'
def SetParameter(self):
self.product.parameter2 = '1-2'
def SetParameter(self):
self.product.parameter3 = '1-3'
def BuildProduct(self):
self.product = Product()
self.SetName()
self.SetParameter1()
self.SetParameter2()
self.SetParameter3()
return self.product
class Direct:
def __init__(self):
self.productBuilder = None
def Build(self):
if self.productBuilder != None:
return self.productBuilder.BuildProduct()
else: return None
def SetBuilder(self, builder):
self.productBuilder = builder
d = Direct()
d.SetBuilder(Product1Builder())
P1 = d.Build()
P2 = d.Build()
print(P1 == P2)
print(id(P1), id(P2))
程式碼說明builder 用來定義改有的生成介面
product 用來定義基本物件形式
product_N_builder 用來詳細定義生成細節
direct 用來設定使用何種builder,並生成。
buildProdut 用來定義生成流程,個人覺得可以放在Direct裡,也可以放在prodcutbuilder裡
留言
張貼留言