使用 內部類 與抽象繼承的方式實現建造者模式,鏈式調用的方式代碼簡潔;
子類繼承實現實際的建造方法方便擴展.
代碼如下:
# -*- coding:utf-8 -*-
import abc
import random
class Product(object):
def __init__(self, product_id=random.random()):
self.uuid = product_id
self.factor = None
self.date = None
def set_factor(self, factor):
self.factor = factor
def set_date(self, date):
self.date = date
# 內部類,作爲建造者類的父類
class Abs_Buildder(object):
def __init__(self):
self.factor = "Default_Factor"
self.date = "Today!"
# 子類實現該方法時必須返回self,用來實現鏈式調用
@abc.abstractmethod
def set_factor(self, factor):
pass
# 子類實現該方法時必須返回self,用來實現鏈式調用
@abc.abstractmethod
def set_date(self, date):
pass
def build_product(self):
product = Product()
product.set_factor(self.factor)
product.set_date(self.date)
return product
# 實際建造者類
class OneBuilder(Product.Abs_Buildder):
def __init__(self):
super(OneBuilder, self).__init__()
def set_factor(self, factor):
print("one factor")
self.factor = factor
return self
def set_date(self, date):
print("One_date")
self.date = date
return self
# 實際建造者類
class TwoBuilder(Product.Abs_Buildder):
def __init__(self):
super(TwoBuilder, self).__init__()
def set_factor(self, factor):
print("Two_Factor")
self.factor = factor
return self
def set_date(self, date):
print("Two_date")
self.date = date
return self
if __name__ == "__main__":
one_b = OneBuilder()
two_b = TwoBuilder()
product1 = OneBuilder().set_factor("1").set_date("yoyo1").build_product()
print(product1)
product2 = TwoBuilder().set_factor("2").set_date("gaga2").build_product()
print(product2)
exit(0)
運行一下:
C:\Python27\python.exe D:/代碼/python-DP/builder-test.py
one factor
One_date
<__main__.Product object at 0x033651B0>
Two_Factor
Two_date
<__main__.Product object at 0x03365290>
Process finished with exit code 0