适用情境:基类定义逻辑框架,子类实现具体步骤.
// ctemplatemethod.h
#ifndef CTEMPLATEMETHOD_H
#define CTEMPLATEMETHOD_H
class CTemplateMethod
{
public:
CTemplateMethod();
virtual void TemplateProcess();
virtual void Operation01() = 0;
virtual void Operation02() = 0;
virtual void Operation03() = 0;
};
#endif // CTEMPLATEMETHOD_H
// ctemplatemethod.cpp
#include "ctemplatemethod.h"
CTemplateMethod::CTemplateMethod()
{}
void CTemplateMethod::TemplateProcess()
{
Operation01();
Operation02();
Operation03();
}
// concreteprocess.h
#ifndef CONCRETEPROCESS_H
#define CONCRETEPROCESS_H
#include "ctemplatemethod.h"
class ConcreteProcess : public CTemplateMethod
{
public:
ConcreteProcess();
virtual void Operation01();
virtual void Operation02();
virtual void Operation03();
};
#endif // CONCRETEPROCESS_H
// concreteprocess.cpp
#include "concreteprocess.h"
#include <iostream>
ConcreteProcess::ConcreteProcess()
{}
void ConcreteProcess::Operation01()
{
std::cout << "operation 01" << std::endl;
}
void ConcreteProcess::Operation02()
{
std::cout << "operation 02" << std::endl;
}
void ConcreteProcess::Operation03()
{
std::cout << "operation 03" << std::endl;
}
客户端:
// main.cpp
#include <iostream>
#include "concreteprocess.h"
using namespace std;
int main(int argc, char *argv[])
{
CTemplateMethod * process = new ConcreteProcess();
process->TemplateProcess();
return 0;
}