一、内容
将一个复杂对象的构建与它表示分离,使得同样的构建过程可以创建不同的表示
二、角色
- 抽象建造者
- 具体建造者
- 指挥者
- 产品
建造者模式与抽象工厂模式相似,也用来创建复杂对象。主要区别是建造者模式着重一步步构造一个复杂对象,而抽象工厂模式着重于多个系列的产品对象。
三、优点
- 隐藏了一个产品的内部结构和装配过程
- 将构造代码与表示代码分开
- 可以将构建过程进行更精细的控制
五、使用场景
- 当创建复杂对象的算法(Director)应该独立于该对象的组成部分以及它们的装配方式(Builder)时
- 当构造过程允许被构造的对象有不同的表示时(不同Builder)
六、代码示例
import random from abc import abstractmethod, ABCMeta #------产品------ class Player: def __init__(self, face=None, body=None, arm=None, leg=None): self.face = face self.arm = arm self.leg = leg self.body = body def __str__(self): return "%s, %s, %s, %s" % (self.face, self.arm, self.body, self.leg) #------建造者------ class PlayerBuilder(metaclass=ABCMeta): @abstractmethod def build_face(self): pass @abstractmethod def build_arm(self): pass @abstractmethod def build_leg(self): pass @abstractmethod def build_body(self): pass @abstractmethod def get_player(self): pass class BeautifulWomanBuilder(PlayerBuilder): def __init__(self): self.player = Player() def build_face(self): self.player.face = "漂亮脸蛋" def build_arm(self): self.player.arm="细胳膊" def build_body(self): self.player.body="细腰" def build_leg(self): self.player.leg="长腿" def get_player(self): return self.player class RandomPlayerBuilder(PlayerBuilder): def __init__(self): self.player = Player() def build_face(self): self.player.face = random.choice(["瓜子脸","西瓜子脸"]) def build_arm(self): self.player.arm=random.choice(["长胳膊","短胳膊"]) def build_body(self): self.player.body=random.choice(["苗条","胖"]) def build_leg(self): self.player.leg=random.choice(["长腿","短腿"]) def get_player(self): return self.player class PlayerDirector: def __init__(self, builder): self.builder = builder # 控制组装顺序 def build_player(self): self.builder.build_body() self.builder.build_face() self.builder.build_arm() self.builder.build_leg() return self.builder.get_player() pd = PlayerDirector(RandomPlayerBuilder()) p = pd.build_player() print(p)