python设计模式-模板方法模式
首先先介绍一下咖啡和茶的冲泡方法: 茶 1. 把水煮沸 2. 用沸水浸泡茶叶 3. 把茶放到杯子里 咖啡 1. 把水煮沸 2. 用沸水冲泡咖啡 3. 把咖啡倒进杯子 4. 加糖和牛奶 用python代码实现冲泡方法大概是这个样子: # 茶的制作方法 class Tea: def prepare_recipe(self): # 在下边实现具体步骤 self.boil_water() self.brew_tea_bag() self.pour_in_cup() def boil_water(self): print("Boiling water") def brew_tea_bag(self): print("Steeping the tea") def pour_in_cup(self): print("Pouring into cup") # 咖啡的制作方法 class Coffee: def prepare_recipe(self): # 在下边实现具体步骤 self.boil_water() self.brew_coffee_grinds() self.pour_in_cup() self.add_sugar_and_milk() def boil_water(self): print("Boiling water") def brew_coffee_grinds(self): print("Dripping Coffee through filter") def pour_in_cup(self): print("Pouring into cup") def add_sugar_and_milk(self): print("Adding Sugar and Milk") 仔细看上边两端代码会发现,茶和咖啡的实现方式基本类似,都有prepare_recipe,boil_water,pour_in_cup 这三个方法。 ...