关键在于把一个算法分解为几个非常固定的步骤,顺序是可以在子类中得到改变的
#include <cstdlib>
#include <iostream>
using namespace std;
class Template
{
public:
virtual ~Template(){cout<<"Tempalte基类析构"<<endl;}
void BiaoBai()
{
SayOneWord();
SayTwoWord();
SayThreeWord();
}
virtual void SayOneWord() = 0;
virtual void SayTwoWord() = 0;
virtual void SayThreeWord() = 0;
};
class Chinese:public Template
{
public:
virtual ~Chinese(){cout<<"Chinese基类析构"<<endl;}
virtual void SayOneWord(){cout<<"I ";}
virtual void SayTwoWord(){cout<<"LOVE ";}
virtual void SayThreeWord(){cout<<"YOU!"<<endl;}
};
class English:public Template
{
public:
virtual ~English(){cout<<"English基类析构"<<endl;}
virtual void SayOneWord(){cout<<"我";}
virtual void SayTwoWord(){cout<<"爱";}
virtual void SayThreeWord(){cout<<"你!"<<endl;}
};
void Do(Template* pBoy)
{
pBoy->BiaoBai();
}
int main(int argc, char *argv[])
{
Template* pOne = new Chinese;
Do(pOne);
delete pOne;
pOne = new English;
Do(pOne);
delete pOne;
system("PAUSE");
return EXIT_SUCCESS;
}