1、作用
做一件是的方法很多,但做这件都可以归纳为几个步骤。这个时候可以使用模板模式,在模板类中,定义做事的步骤,将多种实现做事的细节延迟到子类中去实现。
即:定义一个操作中的算法的骨架(模板函数),而将一些步骤延迟到子类中(基本函数)。模板方法使得子类可以不改变一个算法的结构(模板函数)即可重定义该算法的实现方式(基本函数)。
开闭原则:对修改关闭、对扩展开发
依赖倒置(DIP dependency inversion principle):高层次模块不依赖与低层次模块(调用模块不依赖于被调用模块的修改和扩展,如果被调用模块是基于抽象类开发,那么调用模块只要基于抽象类调用即可。这样就出现了依赖倒置,即具体的类要依赖于抽象的类来实现,而不是抽象类或者调用模块依赖于被调用模块)。依赖倒置的原则就是:子类依赖于抽象基类实现,调用模块依赖于抽象基类调用,这样隔离了调用模块与具体实现的子类的依赖。(要求抽象基类定义的很好)
2、实现方式
比如做菜都分3个步骤:洗菜、切菜、炒菜。
但是做不同的菜每个步骤的细节不一样,这个时候就可以使用模板模式,在模板类(cook)中,将这三个步骤定义为纯虚函数(基本函数)、同时实现一个final的模板函数调用基本函数(洗菜、切菜、炒菜这三个顺序是固定的)。在实现炒不同菜的时候都通过继承这个模板,并根据每个菜的特定实现洗菜、切菜、炒菜三个基本函数。通过模板扩展可以实现炒不同的菜、且有一个统一的接口,方便扩展、使用和维护。
这里将模板函数定义为public的,而基本函数定义为protected的只用于给模板函数调用。
3、C++代码
DoDishTemplate.h
#include <iostream> #ifndef __DO_DISH_TEMPLATE__H__ #define __DO_DISH_TEMPLATE__H__ using namespace std; class DoDishTemplate { // 定义一个顶层框架,模板类定了执行基本函数的模板函数,而把基本函数的实现延迟到子类。 protected: virtual void wash() = 0; // 具体逻辑步骤的函数---->基本函数 virtual void cut() = 0; virtual void cook() = 0; public: virtual void doDish() final { // 将基本方法汇总起来的函数---->模板函数,为了防止恶意操作,模板函数都定义成final的。 cout<<"step 1:"; wash(); cout<<"step 2:"; cut(); cout<<"step 3:"; cook(); } }; // 封装不可变部分:模板函数 扩展可变部分:基本函数 class PotatoFloss : public DoDishTemplate { protected: void wash() override { cout<<"washing potatoes and remove the peel."<<endl; } void cut() override { cout<<"cut the potatoes into silk."<<endl; } void cook() override { cout<<"fried potato slices, add some vinegar."<<endl; } }; class TomatoWithEggs : public DoDishTemplate { protected: void wash() override { cout<<"washing tomatoes."<<endl; } void cut() override { cout<<"cut tomatoes into pieces, beat eggs."<<endl; } void cook() override { cout<<"mix tomatoes and eggs together, then fry."<<endl; } }; #endif
test.cc
#inlcude "DoDishTemplate.h" int main() { DoDishTemplate *doDish = new PotatoFloss; doDish->doDish(); doDish = new TomatoWithEggs; doDish->doDish(); return 0; }
输出: