首先上代碼
# Director
class Director(object):
def __init__(self):
self.builder = None
def construct_building(self):
self.builder.new_building()
self.builder.build_brand()
self.builder.build_size()
self.builder.build_ssd()
def get_building(self):
return self.builder.computer_building
# Abstract Builder
class Computer(object):
def __init__(self):
self.computer_building = None
def new_building(self):
self.computer_building = ComputerBuilding()
# Concrete Builder
class Apple(Computer):
def build_brand(self):
self.computer_building.brand = 'Apple'
def build_size(self):
self.computer_building.size = '15寸'
def build_ssd(self):
self.computer_building.ssd = '256G'
class Acer(Computer):
def build_brand(self):
self.computer_building.brand = 'Acer'
def build_size(self):
self.computer_building.size = '17寸'
def build_ssd(self):
self.computer_building.ssd = '512G'
# Product
class ComputerBuilding(object):
def __init__(self):
self.brand = None
self.size = None
self.ssd = None
def __repr__(self):
return 'Brand: %s | Size: %s | Ssd: %s' % (self.brand, self.size, self.ssd)
# Client
if __name__ == "__main__":
# 指揮者
director = Director()
# 新建個蘋果建造者
director.builder = Apple()
director.construct_building()
building = director.get_building()
print(building)
# 新建宏基建造者
director.builder = Acer()
director.construct_building()
building = director.get_building()
print(building)
建造這主要有三個類:
1.指揮者
2.建造者
3.建造的東西(抽象出來一個抽象類)
就從例子里面來說:
1.指揮者
2.建造電腦的
3.電腦類(抽象了一個電腦類)
過程:
指揮者負(fù)責(zé)只會建造者的一系列動作,然后建造者負(fù)責(zé)電腦的組建有哪些,然后個電腦類開始建造晨横,
電腦類可以擴(kuò)展更多的功能洪囤,比如升級其它的徒坡。
在抽象工廠模式中,抽象出了創(chuàng)建方法瘤缩,使用者只能按照預(yù)定好的步驟新創(chuàng)建一個對象喇完。
在建造者模式中,使用者可以按照自己的想法剥啤,在合理的范圍內(nèi)定制自己所需要的對象锦溪。
所以當(dāng)有一下情況時候不脯,需要考慮使用建造者模式:
1.對象的創(chuàng)建步驟可以獨(dú)立于創(chuàng)建過程的時候
2.被創(chuàng)建的對象擁有不同的表現(xiàn)形式