模板方法模式
不知道你有没有注意过,我们实现某个业务功能,在不同的对象会有不同的细节实现, 以前说过策略模式, 策略模式是将逻辑封装在一个类(提到的文章中的Duck)中,然后使用委托的方式解决。 模板方法模式的角度是:把不变的框架抽象出来,定义好要传入的细节的接口. 各产品类的公共的行为 会被提出到公共父类,可变的都在这些产品子类中
示例
import six
class AlooDish(object):
def get_ingredients(self,):
self.ingredients = {}
def prepare_vegetables(self,):
for item in six.iteritems(self.ingredients):
print("take {0} {1} and cut into smaller pieces".format(item[0],item[1]))
print("cut all vegetables in small pieces")
def fry(self,):
print("fry for 5 minutes")
def serve(self,):
print("Dish is ready to be served")
def cook(self,):
self.get_ingredients()
self.prepare_vegetables()
self.fry()
self.serve()
class AlooMatar(AlooDish):
def get_ingredients(self,):
self.ingredients = {'aloo':"1 Kg",'matar':"1/2 kg"}
def fry(self,):
print("wait 10 min")
class AlooPyaz(AlooDish):
def get_ingredients(self):
self.ingredients = {'aloo':"1 Kg",'pyaz':"1/2 kg"}
aloomatar = AlooMatar()
aloopyaz = AlooPyaz()
print("******************* aloomatar cook")
aloomatar.cook()
print("******************* aloopyaz cook")
aloopyaz.cook()
在上面的例子中,我们将公共的步骤抽象出来,放在父类中,而将不同的部分,实现在子类中。
输出结果为
******************* aloomatar cook
take aloo 1 Kg and cut into smaller pieces
take matar 1/2 kg and cut into smaller pieces
cut all vegetables in small pieces
wait 10 min
Dish is ready to be served
******************* aloopyaz cook
take pyaz 1/2 kg and cut into smaller pieces
take aloo 1 Kg and cut into smaller pieces
cut all vegetables in small pieces
fry for 5 minutes
Dish is ready to be served
网友评论