1.Template模式解决的问题:对于某一个业务逻辑在不同的对象中有不同的细节实现,但是逻辑的框架是相同的。将逻辑框架放在抽象基类中,并定义好细节的接口,子类中实现细节。Template模式利用多态的概念实现算法细节和高层接口的松耦合。
2.Template Pattern 结构图
3.实现
1 #ifndef _TEMPLATE_H_ 2 #define _TEMPLATE_H_ 3 4 class AbstractClass 5 { 6 public: 7 virtual ~AbstractClass(); 8 void TemplateMethod(); 9 protected: 10 virtual void PrimitiveOperation1() = 0; 11 virtual void PrimitiveOperation2() = 0; 12 AbstractClass(); 13 private: 14 }; 15 16 class ConcreteClass1:public AbstractClass 17 { 18 public: 19 ConcreteClass1(); 20 ~ConcreteClass1(); 21 protected: 22 void PrimitiveOperation1(); 23 void PrimitiveOperation2(); 24 private: 25 }; 26 27 class ConcreteClass2:public AbstractClass 28 { 29 public: 30 ConcreteClass2(); 31 ~ConcreteClass2(); 32 protected: 33 void PrimitiveOperation1(); 34 void PrimitiveOperation2(); 35 private: 36 }; 37 38 #endif
1 #include "Template.h" 2 #include <iostream> 3 using namespace std; 4 AbstractClass::AbstractClass() 5 { 6 7 } 8 AbstractClass::~AbstractClass() 9 { 10 11 } 12 void AbstractClass::TemplateMethod() 13 { 14 this->PrimitiveOperation1(); 15 this->PrimitiveOperation2(); 16 } 17 ConcreteClass1::ConcreteClass1() 18 { 19 20 } 21 ConcreteClass1::~ConcreteClass1() 22 { 23 24 } 25 void ConcreteClass1::PrimitiveOperation1() 26 { 27 cout<<"ConcreteClass1...PrimitiveOperation1"<<endl; 28 } 29 void ConcreteClass1::PrimitiveOperation2() 30 { 31 cout<<"ConcreteClass1...PrimitiveOperation2"<<endl; 32 33 } 34 ConcreteClass2::ConcreteClass2() 35 { 36 37 } 38 ConcreteClass2::~ConcreteClass2() 39 { 40 41 } 42 void ConcreteClass2::PrimitiveOperation1() 43 { 44 cout<<"ConcreteClass2...PrimitiveOperation1"<<endl; 45 } 46 void ConcreteClass2::PrimitiveOperation2() 47 { 48 cout<<"ConcreteClass2...PrimitiveOperation2"<<endl; 49 }
1 #include "Template.h" 2 #include <iostream> 3 using namespace std; 4 5 int main(int argc,char* argv[]) 6 { 7 AbstractClass* p1 = new ConcreteClass1(); 8 AbstractClass* p2 = new ConcreteClass2(); p1->TemplateMethod(); 9 p2->TemplateMethod(); 10 return 0; 11 }