创建型模式
1.建造者模式
from abc import ABC, abstractmethod
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 f"<Player: {self.face}脸 {self.body}身材 {self.arm}胳膊 {self.leg}腿>"
class Builder(ABC):
def __init__(self):
self.player = Player()
@abstractmethod
def build_face(self):
pass
@abstractmethod
def build_body(self):
pass
@abstractmethod
def build_arm(self):
pass
@abstractmethod
def build_leg(self):
pass
class SexGirl(Builder):
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 RecklessUncle(Builder):
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 Wolf(Builder):
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 PlayerDirector:
@staticmethod
def build_player(self, builder ):
builder.build_face()
builder.build_body()
builder.build_arm()
builder.build_leg()
return builder.player
if __name__ == '__main__':
sg = SexGirl()
c = PlayerDirector()
role = c.create_role(sg)
print(role)
<Player: 瓜子脸 苗条身材 纤细胳膊 大长腿>
定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
角色:
- 抽象建造者
- 具体建造者
- 指挥者
- 产品
优点:
- 隐藏了一个产品内部结构和装配过程
- 将构造代码与表示代码分开
- 可以对构造过程进行更加精细的控制
总结
- 建造者模式和抽象工厂模式相似,也用来创建复杂对象,主要区别是建造者模式更着重一步步构造一个复杂对象,而抽象工厂模式更着重于多个系列的产品对象。