建造者模式(python)

"""
建造者模式
对复杂对象进行构建过程和表现层的分离,使得一套构建过程能够创建出不同的对象产品
"""
from abc import ABCMeta, abstractmethod


class Food(object):
    def __init__(self):
        self._has_salt = 0
        self._has_oil = 0
        self._has_water = 0
        pass

    def set_salt(self, value):
        self._has_salt = value

    def set_oil(self, value):
        self._has_oil = value

    def set_water(self, value):
        self._has_water = value

    def eat(self):
        if self._has_oil and self._has_water and self._has_salt:
            print("评论:很好吃")
        else:
            print("评论:不能吃")


class CookBuilder(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        pass

    @abstractmethod
    def put_salt(self):
        pass

    @abstractmethod
    def put_oil(self):
        pass

    @abstractmethod
    def put_water(self):
        pass


class GoodCookBuilder(CookBuilder):
    def __init__(self):
        super(GoodCookBuilder, self).__init__()
        self.food = Food()

    def put_salt(self):
        print("放合适的盐")
        self.food.set_salt(1)

    def put_oil(self):
        print("放合适的油")
        self.food.set_oil(1)

    def put_water(self):
        print("放合适的水")
        self.food.set_water(1)

    def get_food(self):
        return self.food


class BadCookBuilder(CookBuilder):
    def __init__(self):
        super(BadCookBuilder, self).__init__()
        self.food = Food()

    def put_salt(self):
        print("放太多盐")
        self.food.set_salt(0)

    def put_oil(self):
        print("没放油")
        self.food.set_oil(0)

    def put_water(self):
        print("水放的挺好")
        self.food.set_water(1)

    def get_food(self):
        return self.food


class CookDirector(object):
    def __init__(self):
        pass

    def cook(self, cook_builder):
        cook_builder.put_salt()
        cook_builder.put_oil()
        cook_builder.put_water()


if __name__ == '__main__':
    # 先有个大厨(指挥者)
    cook_director = CookDirector()
    # 有个做好吃饭的流程
    good_cook_builder = GoodCookBuilder()
    # 大厨指挥做好吃的饭
    cook_director.cook(good_cook_builder)
    # 把经过一系列做饭流程做好的饭拿出来
    good_food = good_cook_builder.get_food()
    # 吃下饭,发表意见
    good_food.eat()
    print("")
    # ####做不好吃的饭
    bad_cook_builder = BadCookBuilder()
    cook_director.cook(bad_cook_builder)
    bad_food = bad_cook_builder.get_food()
    bad_food.eat()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值