template method (模板方法)
模板方法是很基础的一种设计模式,主要应对的问题是:
- 主流程基本不变
- 部分步变化性大
其实这种问题十分常见,比如,一个网络请求的处理过程(不知道合适不合适):
- 步骤1,接受请求
- 步骤2,处理请求,实现业务逻辑(变化的)
- 步骤3,返回步骤2的数据给客户端
实际上就是一个c++多态的应用
#include <iostream>
#include <string>
using namespace std;
//基类server
class server
{
public:
//主流程不变
void run()
{
step1();
step3(step2());
}
protected:
void step1()
{
cout<<"接受请求"<<endl;
}
virtual string step2()=0;
void step3(string res) {
cout<<"返回数据:"<<res<<endl;
}
virtual ~server()
{
}
};
//处理1
class http:public server
{
virtual string step2()
{
return "http 数据";
}
};
//处理2
class json:public server
{
virtual string step2()
{
return "json 数据";
}
};
int main(int argc, char const *argv[]) {
http* hp = new http();
hp->run();
json* jp = new json();
jp->run();
return 0;
}
template.png