在GOF的《设计模式:可复用面向对象软件的基础》一书中对模板方法模式是这样说的:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。TemplateMethod使得子类可以不改变一个算法的接口即可重定义改算法的某些特定步骤。模板方法简单来说就是在基类中定义一个算法模型,该模型又包含多个算法部分,而各个算法的实现不是在该基类中完成,而是通过继承类对该算法的重定义函数实现,从而实现不同的算法。
UML类图
例如在具体的实例中,mybasicclass基类中有个TemplateMethod()方法,该方法定义了一个算法模型,在该算法中调用了OneOperation()和TwoOperation()两个成员方法,也可将其视为算法的接口,这些成员方法组成了整个算法的各个部分。这些成员方法则可以根据子类的不同而实现不同的改变。模板方法模式提供了一个很好的代码复用方法。
#ifndef MYBASICCLASS_H
#define MYBASICCLASS_H
#include <iostream>
using namespace std;
//抽象基类 实现一个模板的方法
class mybasicclass
{
public:
virtual~mybasicclass()
{
}
//模板方法 ,只在抽象基类中实现
void TemplateMethod()
{
cout<<"OneOperation"<<endl;
this->OneOperation();
cout<<"TwoOperation"<<endl;
this->TwoOperation();
}
protected:
virtual void OneOperation() = 0;
virtual void TwoOperation() = 0;
mybasicclass()
{
}
};
class ConsonclassOne:public mybasicclass
{
public:
ConsonclassOne()
{
}
~ConsonclassOne()
{
}
protected:
void OneOperation()
{
cout<<"ConcreteClassOne...PrimitiveOperationOne"<<endl;
}
void TwoOperation()
{
cout<<"ConcreteClassOne...PrimitiveOperationTwo"<<endl;
}
};
class ConsonclassTwo:public mybasicclass
{
public:
ConsonclassTwo()
{
}
~ConsonclassTwo()
{
}
protected:
void OneOperation()
{
cout<<"ConcreteClassTwo...PrimitiveOperationOne"<<endl;
}
void TwoOperation()
{
cout<<"ConcreteClassTwo...PrimitiveOperationTwo"<<endl;
}
};
#endif // MYBASICCLASS_H
#include <iostream>
#include "mybasicclass.h"
using namespace std;
int main()
{
mybasicclass * p1 =new ConsonclassOne();
mybasicclass * p2 = new ConsonclassTwo();
p1->TemplateMethod();
p2->TemplateMethod();
cout << "Hello World!" << endl;
return 0;
}