模板模式即定义一个操作中的算法的骨架,而将一些具体步骤延迟到子类中。模板使得子类可以不改变一个算法的结构即可重新定义算法的某些特定步骤。
例如,现在老师在黑板上写题目,学生们要把题目抄到本子上,并且写下自己的答案,我们可以把抄题目和写答案放到父类,而所给出的答案放到子类
/*************************************************************************Title.h*******************************************************************************************/
#include <iostream>
#include <string>
#pragma once;
using namespace std;
class Title
{
public:
void TestQuestion()
{
cout<<"程序员最喜欢的事:A、编码 B、撩妹 C、偷懒"<<endl;
cout<<"您选择的答案是:"<<answer()<<endl;
};
virtual string answer() = 0;
};
/************************************************************************StudentA.h*******************************************************************************************/
#include "Title.h"
class StudentA : public Title
{
public:
string answer()
{
return "A";
}
};
/************************************************************************StudentB.h*******************************************************************************************/
#include "Title.h"
class StudentB : public Title
{
public:
string answer()
{
return "C";
}
};
/************************************************************************main.cpp*******************************************************************************************/
#include "StudentA.h"
#include "StudentB.h"
int main()
{
Title *studentA = new StudentA;
Title *studentB = new StudentB;
studentA->TestQuestion();
studentB->TestQuestion();
getchar();
return 0;
}