template模式
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 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步