"""
建造者模式
对复杂对象进行构建过程和表现层的分离,使得一套构建过程能够创建出不同的对象产品
"""
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()
建造者模式(python)
最新推荐文章于 2024-09-29 13:32:57 发布