相关模式:思路和模板方法模式很像,模板方法是封装算法流程,对某些细节,提供接口由子类修改,建造者模式更为高层一点,将所有细节都交由子类实现。
代码:
#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()
return
if __name__ == '__main__':
clientUI();
类图: