1 #include <iostream> 2 using namespace std; 3 class AbstractClass { 4 public: 5 AbstractClass() { 6 } 7 virtual ~AbstractClass() { 8 } 9 // 这个函数中定义了算法的轮廓 10 void TemplateMethod(); 11 protected: 12 // 纯虚函数,由派生类实现之 13 virtual void PrimitiveOperation1() = 0; 14 virtual void PrimitiveOperation2() = 0; 15 }; 16 // 继承自AbstractClass,实现算法 17 class ConcreateClass: public AbstractClass { 18 public: 19 ConcreateClass() { 20 } 21 virtual ~ConcreateClass() { 22 } 23 protected: 24 virtual void PrimitiveOperation1(); 25 virtual void PrimitiveOperation2(); 26 }; 27 28 void AbstractClass::TemplateMethod() { 29 PrimitiveOperation1(); 30 PrimitiveOperation2(); 31 } 32 void ConcreateClass::PrimitiveOperation1() { 33 cout << "PrimitiveOperation1 by ConcreateClass\n"; 34 } 35 void ConcreateClass::PrimitiveOperation2() { 36 cout << "PrimitiveOperation2 by ConcreateClass\n"; 37 } 38 39 int main() { 40 AbstractClass* pConcreateClass = new ConcreateClass; 41 pConcreateClass->TemplateMethod(); 42 delete pConcreateClass; 43 return 0; 44 }