设计模式——建造者模式

创建型模式

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"{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: 瓜子脸 苗条身材 纤细胳膊 大长腿>

定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示

角色:

  1. 抽象建造者
  2. 具体建造者
  3. 指挥者
  4. 产品

优点:

  1. 隐藏了一个产品内部结构和装配过程
  2. 将构造代码与表示代码分开
  3. 可以对构造过程进行更加精细的控制

总结

  • 建造者模式和抽象工厂模式相似,也用来创建复杂对象,主要区别是建造者模式更着重一步步构造一个复杂对象,而抽象工厂模式更着重于多个系列的产品对象。

你可能感兴趣的:(设计模式,设计模式,建造者模式,python)