实现外观模式示例,添加相关类和方法,增强代码可读性
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
"""
|
||||
实例
|
||||
汤宝宝教你番茄炒蛋~
|
||||
"""
|
||||
|
||||
class TomatoEgg:
|
||||
def serve(self):
|
||||
print("番茄炒蛋上桌啦!")
|
||||
|
||||
class CutTomato:
|
||||
def cut(self):
|
||||
print("番茄切好了!")
|
||||
|
||||
class BeatEgg:
|
||||
def beat(self):
|
||||
print("鸡蛋打好了!")
|
||||
|
||||
class Cook:
|
||||
cutTomato: CutTomato
|
||||
beatEgg: BeatEgg
|
||||
|
||||
def __init__(self,cutTomato: CutTomato, beatEgg: BeatEgg) -> None:
|
||||
self.cutTomato = cutTomato
|
||||
self.beatEgg = beatEgg
|
||||
|
||||
def cook_dish(self):
|
||||
self.cutTomato.cut()
|
||||
self.beatEgg.beat()
|
||||
print("食材放入锅中,开火加热。")
|
||||
print("番茄炒蛋炒好了。")
|
||||
|
||||
# 外观
|
||||
class ChefFacade:
|
||||
cook: Cook
|
||||
dish: TomatoEgg
|
||||
def __init__(self) -> None:
|
||||
self.cook = Cook(CutTomato(), BeatEgg())
|
||||
self.dish = TomatoEgg()
|
||||
|
||||
def prepare_and_serve(self):
|
||||
print("准备食材...")
|
||||
self.cook.cook_dish()
|
||||
self.dish.serve()
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("============= 外观模式 =============")
|
||||
chef = ChefFacade()
|
||||
chef.prepare_and_serve()
|
||||
print("\n=========== 外观模式结束 ===========")
|
||||
Reference in New Issue
Block a user