將一個(gè)復(fù)雜對(duì)象的構(gòu)建與它的表示分離诲泌,使得同樣的構(gòu)建過程可以創(chuàng)建不同的表示。
相關(guān)模式:思路和模板方法模式很像伸眶,模板方法是封裝算法流程惊窖,對(duì)某些細(xì)節(jié),提供接口由子類修改厘贼,建造者模式更為高層一點(diǎn)界酒,將所有細(xì)節(jié)都交由子類實(shí)現(xiàn)
一個(gè)例子更能很好的理解以上的內(nèi)容:
- 有一個(gè)接口類,定義創(chuàng)建對(duì)象的方法嘴秸。一個(gè)指揮員類毁欣,接受創(chuàng)造者對(duì)象為參數(shù)。兩個(gè)創(chuàng)造者類赁遗,創(chuàng)建對(duì)象方法相同署辉,內(nèi)部創(chuàng)建可自定義
2.一個(gè)指揮員,兩個(gè)創(chuàng)造者(瘦子 胖子)岩四,指揮員可以指定由哪個(gè)創(chuàng)造者來創(chuàng)造
from abc import ABCMeta, abstractmethod
class Builder():
__metaclass__ = ABCMeta
@abstractmethod
def draw_left_arm(self):
pass
@abstractmethod
def draw_right_arm(self):
pass
@abstractmethod
def draw_left_foot(self):
pass
@abstractmethod
def draw_right_foot(self):
pass
@abstractmethod
def draw_head(self):
pass
@abstractmethod
def draw_body(self):
pass
class Thin(Builder):
def draw_left_arm(self):
print '畫左手'
def draw_right_arm(self):
print '畫右手'
def draw_left_foot(self):
print '畫左腳'
def draw_right_foot(self):
print '畫右腳'
def draw_head(self):
print '畫頭'
def draw_body(self):
print '畫瘦身體'
class Fat(Builder):
def draw_left_arm(self):
print '畫左手'
def draw_right_arm(self):
print '畫右手'
def draw_left_foot(self):
print '畫左腳'
def draw_right_foot(self):
print '畫右腳'
def draw_head(self):
print '畫頭'
def draw_body(self):
print '畫胖身體'
class Director():
def __init__(self, person):
self.person=person
def draw(self):
self.person.draw_left_arm()
self.person.draw_right_arm()
self.person.draw_left_foot()
self.person.draw_right_foot()
self.person.draw_head()
self.person.draw_body()
if __name__=='__main__':
thin=Thin()
fat=Fat()
director_thin=Director(thin)
director_thin.draw()
director_fat=Director(fat)
director_fat.draw()