本文實例講述了Python實現的建造者模式。分享給大家供大家參考,具體如下:
#!/usr/bin/python# -*- coding:utf-8 -*-#建造者基類class PersonBuilder(): def BuildHead(self): pass def BuildBody(self): pass def BuildArm(self): pass def BuildLeg(self): pass#胖子class PersonFatBuilder(PersonBuilder): type = u'胖子' def BuildHead(self): print u'構建%s的頭' % self.type def BuildBody(self): print u'構建%s的身體' % self.type def BuildArm(self): print u'構建%s的手' % self.type def BuildLeg(self): print u'構建%s的腳' % self.type#瘦子class PersonThinBuilder(PersonBuilder): type = u'瘦子' def BuildHead(self): print u'構建%s的頭' % self.type def BuildBody(self): print u'構建%s的身體' % self.type def BuildArm(self): print u'構建%s的手' % self.type def BuildLeg(self): print u'構建%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();
運行結果:
構建瘦子的頭
構建瘦子的身體
構建瘦子的手
構建瘦子的腳
構建胖子的頭
構建胖子的身體
構建胖子的手
構建胖子的腳
更多關于Python相關內容可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答