Python设计模式(1)设计模式简介与分类
Python设计模式(2)简单工厂模式
Python设计模式(3)工厂方法模式
Python设计模式(4)抽象工厂模式
Python设计模式(5)建造者模式
Python设计模式(6)单例模式
1、建造者模式简介
- 含义:
将一个复杂对象的构建与他的表示分离,使得同样的构建过程可以创建不同的表示 - 优点:
隐藏了一个产品的内部结构和装配过程
将构造代码与表示代码分开
可以对构造过程进行更加精准的控制
2、代码实现:
代码如下:
from abc import ABCMeta,abstractmethod
class Player(object):
def __init__(self,face="",body="",arm="",leg=""):
self.face=face
self.body=body
self.arm=arm
self.leg=leg
def __str__(self):
return f"face:{self.face}, body:{self.body}, arm:{self.arm}, leg:{self.leg}."
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(selfj):
pass
class SexyGirlBuilder(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 __str__(self):
return f"face:{self.player.face}, arm:{self.player.arm}, body:{self.player.body}, leg:{self.player.leg}"
class Monster(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 = "后退"
class PlayerDirector(object):
def build_player(self,builder):
builder.build_body()
builder.build_arm()
builder.build_face()
builder.build_leg()
return builder
if __name__=="__main__":
builder=SexyGirlBuilder()
director=PlayerDirector()
p=director.build_player(builder)
print(p)