1 | 2 |
---|---|
定义 | 使用多个简单的对象一步一步构建成一个复杂的对象 |
应用场景 | 1、去肯德基,汉堡、可乐、薯条、炸鸡翅等是不变的,而其组合是经常变化的,生成出所谓的"套餐 |
角色 | 抽象建造者(Builder) 具体建造者(Concrete Builder) 指挥者(Director) 产品(product) |
优点 | 1.隐藏了一个产品的内部结构和装配过程 2.将构造代码与表示代码分开 3.可以对构造过程进行更精细的控制 注意建造者模式与抽象工厂模式相似,也是用来创建复杂对象,主要是建造者模式着重一步一步构造复杂的对象,而抽象工厂模式着重于多个系列的产品对象 |
缺点 | 1、产品必须有共同点,范围有限制。 2、如内部变化复杂,会有很多的建造类。 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from abc import abstractmethod, ABCMeta
# 产品
class Player:
def __init__(self, face=None, body=None, arm=None, leg=None):
self.face = face
self.body = body
self.arm = arm
self.leg = leg
def __str__(self):
return "%s,%s,%s,%s" % (self.face, self.body, self.arm, self.leg)
# -----抽象创建者-----
class PlayerBuilder(metaclass=ABCMeta):
@abstractmethod
def build_body(self):
pass
@abstractmethod
def build_face(self):
pass
@abstractmethod
def build_arm(self):
pass
@abstractmethod
def build_leg(self):
pass
# -----具体创建者-----
class SexyGirlBuilder(PlayerBuilder):
def __init__(self):
self.player = Player()
def build_body(self):
self.player.body = "好的身体"
def build_face(self):
self.player.face = "好的脸蛋"
def build_arm(self):
self.player.arm = "好的手臂"
def build_leg(self):
self.player.leg = "好的腿"
class MonsterBuilder(PlayerBuilder):
def __init__(self):
self.player = Player()
def build_body(self):
self.player.body = "不好的身体"
def build_face(self):
self.player.face = "不好的脸蛋"
def build_arm(self):
self.player.arm = "不好的手臂"
def build_leg(self):
self.player.arm = "不好的腿"
# -----指挥者-----
class PlayerDirector:
@staticmethod
def build_player(builder):
builder.build_body()
builder.build_face()
builder.build_arm()
builder.build_leg()
return builder.player
if __name__ == '__main__':
# client
builder1 = SexyGirlBuilder()
director = PlayerDirector()
p = director.build_player(builder1)
print(p)