模板方法模式:定义了操作中的算法的骨架,而将一些步骤延迟子类中。模板方法使得子类可以不改变一个算法,即可重定义该算法的某些特定步骤。
当我们完成在某一细节层次一致的一个过程或是一系列步骤时,个别步骤在更详细的层次上实现可能不同时,通常考虑用模板方法模式。
模板方法是通过把不变的行为搬到基类,取出子类的重复代码来实现它的优势。它提供了一个很好的代码复用平台。当不变的和变化的行为在子类中混合到一起实现的时候,不变的行为就会在子类中重复出现。通过模版方法模式将将这些行为搬到单一的地方这样就帮助子类摆脱重复的不变行为的纠缠。
《大话设计模式》在介绍这一模式时举了一个试卷模板的例子。对于所有学生来说试卷都是相同的,不同就是每个学生的答案可能是不相同的,这时就可以将相同的操作抽象到更高一级的基类中,避免了重复代码的使用。在使用MFC或是osg类库时,经常遇到这种情况:一个继承体系的基类声明了很多成员函数,而这些都是子类共同具有的方法。如CWnd类。
#include<iostream>
using namespace std;
class TestPaper
{
public:
TestPaper()
{
}
void Question1()
{
cout<<"问题1:******************"<<endl;
cout<<"答案:"<<answer1()<<endl;
}
void Question2()
{
cout<<"问题1:******************"<<endl;
cout<<"答案:"<<answer2()<<endl;
}
void Question3()
{
cout<<"问题2:******************"<<endl;
cout<<"答案:"<<answer3()<<endl;
}
virtual char answer1()=0;
virtual char answer2()=0;
virtual char answer3()=0;
};
class StudentA:public TestPaper
{
public:
StudentA()
{
}
virtual char answer1()
{
return 'A';
}
virtual char answer2()
{
return 'C';
}
virtual char answer3()
{
return 'D';
}
};
class StudentB:public TestPaper
{
public:
StudentB()
{
}
virtual char answer1()
{
return 'B';
}
virtual char answer2()
{
return 'A';
}
virtual char answer3()
{
return 'C';
}
};
int main(int argc,char**argv)
{
cout<<"学生A的试卷:"<<endl;
TestPaper *stuA=new StudentA;
stuA->Question1();
stuA->Question2();
stuA->Question3();
cout<<"学生B的试卷:"<<endl;
TestPaper *stuB=new StudentB;
stuB->Question1();
stuB->Question2();
stuB->Question3();
return 0;
}