设计模式:Temple Method(模板方法)
模板方法意图:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。模板方法可以使子类不改变算法结构即可重新定义该算法的某些特定步骤。
理解不够深刻,以后再回来编辑。
TemplateMethod.cpp #include <iostream> #include "MyApplication.h" #include "MyLibrary.h" int main() { std::cout << "Hello World!\n"; MyLibrary *m = new MyApplication(); m->run(); return 0; }
MyLibrary.h #pragma once #include<iostream> using namespace std; class MyLibrary { public: void run(); protected: void fun1(); void fun3(); void fun5(); virtual bool fun2() = 0; virtual void fun4() = 0; };
MyLibrary.cpp #include "MyLibrary.h" using namespace std; void MyLibrary::fun1() { cout << "这是MyLibrary类方法fun1()"<<endl; } void MyLibrary::fun3() { cout << "这是MyLibrary类方法fun3()"<<endl; } void MyLibrary::fun5() { cout << "这是MyLibrary类方法fun5()"<<endl; } void MyLibrary::run() { fun1(); if (fun2()) fun3(); for (int i = 0; i < 4; i++) { fun4(); } fun5(); }
MyApplication.h #pragma once #include<iostream> #include "MyLibrary.h" using namespace std; class MyApplication : public MyLibrary { protected: virtual bool fun2(); virtual void fun4(); };
MyApplication.cpp #include "MyApplication.h" bool MyApplication::fun2() { cout << "这是MyApplication类的fun2()" << endl; return true; } void MyApplication::fun4() { cout << "这是MyApplication类的fun4()"<<endl; }
运行程序后输出为:
Hello World!
这是MyLibrary类方法fun1()
这是MyApplication类的fun2()
这是MyLibrary类方法fun3()
这是MyApplication类的fun4()
这是MyApplication类的fun4()
这是MyApplication类的fun4()
这是MyApplication类的fun4()
这是MyLibrary类方法fun5()