建造者模式(创建型模式)
内容: 将一个复杂对象的构建与它的表示分离,
使得同样的构建过程可以创建不同的表示,
并且构建的顺序被指挥者所控制.
角色:
- 抽象建造者(Builder)
- 具体建造者(Concrete Builder)
- 指挥者(Director)
- 产品(Product)
与抽象工厂模式区别:
建造者模式与抽象工厂模式相似,也用来创建复杂对象.
主要区别是建造者模式着重一步步有顺序的构造一个复杂对象,
而抽象工厂模式着重于多个系列的产品对象
优点:
- 隐藏了一个产品的内部结构和装配过程
- 将构造代码与表示代码分开
- 可以对构造过程进行更精细的控制
示例
from abc import ABCMeta, abstractmethod
# ----------------------------------------
# Product
# ----------------------------------------
class Player:
"""
Product
"""
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 (f"{self.face}, "
f"{self.body}, "
f"{self.arm}, "
f"{self.leg}.")
# ----------------------------------------
# Builder
# ----------------------------------------
class PlayerBuilder(metaclass=ABCMeta):
@abstractmethod
def build_face(self):
pass
@abstractmethod
def build_body(self):
pass
@abstractmethod
def build_arm(self):
pass
@abstractmethod
def build_leg(self):
pass
# ----------------------------------------
# Concrete Builder
# ----------------------------------------
class SexyGirlBuilder(PlayerBuilder):
def __init__(self):
self.player = Player()
def build_face(self):
self.player.face = '漂亮脸蛋'
def build_body(self):
self.player.body = '苗条'
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_face(self):
print('怪物脸')
def build_body(self):
print('怪物身体')
def build_arm(self):
print('怪物胳膊')
def build_leg(self):
print('怪物腿')
# ----------------------------------------
# Director
# ----------------------------------------
class PlayerDirector:
@staticmethod
def build_player(_builder):
_builder.build_body()
_builder.build_face()
_builder.build_arm()
_builder.build_leg()
return _builder.player
# ----------------------------------------
# client
# ----------------------------------------
builder = SexyGirlBuilder()
director = PlayerDirector()
player = director.build_player(builder)
print(player)
运行结果
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved