C++设计模式之模板模式
定义:定义一个操作中算法的骨架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变算法的结构即可重定义该算法的某些特定步骤。
其实这个设计模式是比较简单的一个密室,换句话来说就是利用虚函数,把一些步骤延迟到子类中进行实现,设计模式中经常会说这么一句话不稳定的函数写成虚函数,稳定的函数写成非虚函数,接下来,我们看看它的类图
Snipaste_2018-11-06_19-45-14.png
接下来,我们用模板模式实现一个函数;
1.在基类中声明虚函数
2.子类继承父类
3.在子类中实现了虚函数
4.子类的添加删除都不会不影响到父类,说明父类是稳定的,带到了设计模式的目的。
1 #include<iostream>
2 using namespace std;
3
4 class TemplateMethod
5 {
6 public:
7 void Template()
8 {
9 cout<<"I am templatemethod"<<endl;
10 }
11 virtual void Print() = 0;//声明虚函数
12 };
13
14 class PrimitiveOperation1:public TemplateMethod //继承父类
15 {
16 public:
17 void Print()
18 {
19 cout<<"I am PrimitiveOperation1"<<endl;
20 }
21 };
22
23 class PrimitiveOperation2:public TemplateMethod //继承父类
24 {
25 public:
26 void Print() //重新编写虚函数
27 {
28 cout<<"I am PrimitiveOperation2"<<endl;
29 }
30
31 };
32
33 int main()
34 {
35 TemplateMethod* method1 = new PrimitiveOperation1(); //实例化
36 method1->Print();
37 TemplateMethod* method2 = new PrimitiveOperation2(); //实例化
38 method2->Print();
39 return 0;
40 }