继续写
"""建造者模式"""
class Director(object):
def __init__(self):
self.builder = None
def construct_building(self):
self.builder.new_building()
self.builder.build_floor()
self.builder.build_size()
def get_building(self):
return self.builder.building
class Builder(object):
def __init__(self):
self.building = None
def new_building(self):
self.building = BuildProduct()
def build_floor(self):
raise NotImplementedError
def build_size(self):
raise NotImplementedError
class BuilderHouse(Builder):
def build_floor(self):
self.building.floor = '一'
def build_size(self):
self.building.size = '大'
class BuilderFlat(Builder):
def build_floor(self):
self.building.floor = '超过一层'
def build_size(self):
self.building.size = '小'
class BuildProduct(object):
def __init__(self):
self.floor = None
self.size = None
"""Python中这个_repr_函数,对应repr(object)这个函数,返回一个可以用来表示对象的可打印字符串"""
def __repr__(self):
return '楼层: {0.floor} | 尺寸: {0.size}'.format(self)
if __name__ == "__main__":
director = Director()
director.builder = BuilderHouse()
director.construct_building()
building = director.get_building()
print(building)
director.builder = BuilderFlat()
director.construct_building()
building = director.get_building()
print(building)
结果如图:
