テンプレートメソッドパターンは、デザインパターンの中で最も一般的に使用されるパターンの1つです。
簡単に言えば、実行フローのセットを定義する基本クラス/抽象クラスであり、フロー内の特定のメソッドの実装は実装クラスに任されています。
使用シナリオには複数のサブカテゴリがあり、特定の操作の処理フローは基本的に同じであるため、このモードを採用できます。
#include <iostream>
using namespace std;
class BaseHttp {
public:
// 在这里 模板方法"Parsing()",定义一个算法的执行流程,
// 先ParsingHead,再ParsingBody,当然也可以有更多的处理函数
// 公共处理的函数放在基类中,
// 需要实现类单独实现的声明为虚函数,由实现类实现
void Parsing() {
ParsingHead();
ParsingBody();
// to-do
}
protected:
virtual void ParsingBody() = 0;
void ParsingHead() {
cout << "Http ParsingHead" << endl; }
};
// 实现类,只需要实现具体工作就可以
class Http1 : public BaseHttp {
protected:
virtual void ParsingBody() final {
cout << "Http1 ParsingBody" << endl; }
};
class Http2 : public BaseHttp {
protected:
virtual void ParsingBody() final {
cout << "Http2 ParsingBody" << endl; }
};
int main() {
BaseHttp *h1 = new Http1();
BaseHttp *h2 = new Http2();
h1->Parsing();
h2->Parsing();
delete h1;
delete h2;
return 0;
}
出力
[root@localhost Demo]# ./TemplateMethodPattern
Http ParsingHead
Http1 ParsingBody
Http ParsingHead
Http2 ParsingBody