Template 模式是很简单模式,但是也应用很广的模式。Template 是采用继承的方式实现算法的异构,其关键点就是将通用算法封装在抽象基类中,并将不同的算法细节放到子类中实现。Template 模式获得一种反向控制结构效果, 这也是面向对象系统的分析和设计中一个原则 DIP(依赖倒置:Dependency Inversion Principles) 。其含义就是父类调用子类的操作(高层模块调用低层模块的操作) ,低层模块实现高层模块声明的接口。这样控制权在父类(高层模块) ,低层模块反而要依赖高层模块。
1 //Template.h//// 2 #pragma once 3 class AbstractClass 4 { 5 public: 6 virtual ~AbstractClass(); 7 void TemplateMethod(); 8 protected: 9 AbstractClass(); 10 virtual void PrimitiveOperation1() = 0; 11 virtual void PrimitiveOperation2() = 0; 12 private: 13 }; 14 15 class ConcreteClass1 :public AbstractClass 16 { 17 public: 18 ~ConcreteClass1(); 19 ConcreteClass1(); 20 protected: 21 void PrimitiveOperation1(); 22 void PrimitiveOperation2(); 23 private: 24 }; 25 26 class ConcreteClass2 :public AbstractClass 27 { 28 public: 29 ~ConcreteClass2(); 30 ConcreteClass2(); 31 protected: 32 void PrimitiveOperation1(); 33 void PrimitiveOperation2(); 34 private: 35 };
1 ///Template.cpp/// 2 #include "Template.h" 3 #include <iostream> 4 using namespace std; 5 AbstractClass::AbstractClass() 6 { 7 8 } 9 AbstractClass::~AbstractClass() 10 { 11 12 } 13 void AbstractClass::TemplateMethod() 14 { 15 this->PrimitiveOperation1(); 16 this->PrimitiveOperation2(); 17 } 18 19 ConcreteClass1::ConcreteClass1() 20 { 21 cout<<"泡茶"<<endl; 22 23 } 24 ConcreteClass1::~ConcreteClass1() 25 { 26 27 } 28 void ConcreteClass1::PrimitiveOperation1() 29 { 30 cout<<"放入茶叶"<<endl; 31 } 32 void ConcreteClass1::PrimitiveOperation2() 33 { 34 cout<<"倒入开水"<<endl; 35 } 36 37 ConcreteClass2::ConcreteClass2() 38 { 39 cout<<"泡咖啡"<<endl; 40 } 41 ConcreteClass2::~ConcreteClass2() 42 { 43 44 } 45 void ConcreteClass2::PrimitiveOperation1() 46 { 47 cout<<"放入咖啡"<<endl; 48 } 49 void ConcreteClass2::PrimitiveOperation2() 50 { 51 cout<<"加适量开水"<<endl; 52 }
1 /main.cpp/ 2 #include "Template.h" 3 #include <iostream> 4 int main() 5 { 6 AbstractClass* a = new ConcreteClass1(); 7 a->TemplateMethod(); 8 AbstractClass* b = new ConcreteClass2(); 9 b->TemplateMethod(); 10 getchar(); 11 }