建造者模式:將一個複雜物件的構建與它的表示分離,使得同樣的構建過程可以建立不同的表示。
相關模式:思路和模板方法模式很像,模板方法是封裝演算法流程,對某些細節,提供介面由子類修改,建造者模式更為高層一點,將所有細節都交由子類實現。
代碼:
#encoding=utf-8##by panda#建造者模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk')#建造者基類class PersonBuilder(): def BuildHead(self): pass def BuildBody(self): pass def BuildArm(self): pass def BuildLeg(self): pass #胖子class PersonFatBuilder(PersonBuilder): type = '胖子' def BuildHead(self): printInfo("構建%s的頭" % self.type) def BuildBody(self): printInfo("構建%s的身體" % self.type) def BuildArm(self): printInfo("構建%s的手" % self.type) def BuildLeg(self): printInfo("構建%s的腳" % self.type) #瘦子class PersonThinBuilder(PersonBuilder): type = '瘦子' def BuildHead(self): printInfo("構建%s的頭" % self.type) def BuildBody(self): printInfo("構建%s的身體" % self.type) def BuildArm(self): printInfo("構建%s的手" % self.type) def BuildLeg(self): printInfo("構建%s的腳" % self.type)#指揮者class PersonDirector(): pb = None; def __init__(self, pb): self.pb = pb def CreatePereson(self): self.pb.BuildHead() self.pb.BuildBody() self.pb.BuildArm() self.pb.BuildLeg()def clientUI(): pb = PersonThinBuilder() pd = PersonDirector(pb) pd.CreatePereson() pb = PersonFatBuilder() pd = PersonDirector(pb) pd.CreatePereson() returnif __name__ == '__main__': clientUI();
類圖: