设计模式-Template(行为模式) 采用 继承的方式 将算法封装在抽象基类中,在子类中实现细节。利用面向对象中的多态实现算法实现细节和高层接口的松耦合。
以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Template.h
class AbstractClass { public: virtual ~AbstractClass(); void TemplateMethod(); protected: virtual void PrimitiveOperation1() = 0; virtual void PrimitiveOperation2() = 0; AbstractClass(); private: }; class ConcreateClass1 :public AbstractClass { public: ConcreateClass1(); virtual ~ConcreateClass1(); protected: void PrimitiveOperation1(); void PrimitiveOperation2(); private: }; class ConcreateClass2 :public AbstractClass { public: ConcreateClass2(); virtual ~ConcreateClass2(); protected: void PrimitiveOperation1(); void PrimitiveOperation2(); private: };
//Template.cpp
#include"Template.h" #include<iostream> AbstractClass::AbstractClass(){} AbstractClass::~AbstractClass(){} void AbstractClass::TemplateMethod() { this->PrimitiveOperation1(); this->PrimitiveOperation2(); } ConcreateClass1::ConcreateClass1(){} ConcreateClass1::~ConcreateClass1(){} void ConcreateClass1::PrimitiveOperation1() { std::cout << "ConcreateClass1 ...PrimitiveOperation1" << std::endl; } void ConcreateClass1::PrimitiveOperation2() { std::cout << "ConcreateClass1 ... PrimitiveOperation2" << std::endl; } ConcreateClass2::ConcreateClass2(){} ConcreateClass2::~ConcreateClass2(){} void ConcreateClass2::PrimitiveOperation1() { std::cout << "ConcreateClass2 ... PrimitiveOperation1" << std::endl; } void ConcreateClass2::PrimitiveOperation2() { std::cout << "ConcreateClass2 ... PrimitiveOperation2" << std::endl; }
//main.cpp
#include"Template.h" #include<iostream> #include<string> int main(int args, char* argv) { ConcreateClass1* p1 = new ConcreateClass1(); ConcreateClass2* p2 = new ConcreateClass2(); p1->TemplateMethod(); p2->TemplateMethod(); getchar(); return 0; }