首页 > 技术文章 > 大话设计模式-模板方法模式

zhangjxblog 2018-04-19 19:27 原文

模板方法模式:

       定义一个操作中的算法的骨架,将一些步骤延迟到之类中。模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。

 1 // Template.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 
 7 using namespace std;
 8 
 9 class TemplateClass{
10 public:
11     virtual void PrimitiveOperation1()=0;
12     virtual void PrimitiveOperation2()=0;
13 
14     void  Method(){
15         PrimitiveOperation1();
16         PrimitiveOperation2();
17     }
18 
19 };
20 
21 class TemplateClassA:public TemplateClass{
22 public:
23     virtual void PrimitiveOperation1();
24     virtual void PrimitiveOperation2();
25 
26 };
27 
28 class TemplateClassB:public TemplateClass{
29 public:
30     virtual void PrimitiveOperation1();
31     virtual void PrimitiveOperation2();
32 
33 };
34 void TemplateClassA::PrimitiveOperation1(){
35     cout << "类A的方法1"<<endl;
36 }
37 void TemplateClassA::PrimitiveOperation2(){
38     cout << "类A的方法2"<<endl;
39 }
40 void TemplateClassB::PrimitiveOperation1(){
41     cout << "类B的方法1"<<endl;
42 }
43 void TemplateClassB::PrimitiveOperation2(){
44     cout << "类B的方法2"<<endl;
45 }
46 int _tmain(int argc, _TCHAR* argv[])
47 {
48     TemplateClass *a = new TemplateClassA();
49     TemplateClass *b = new TemplateClassB();
50 
51     a->Method();
52     b->Method();
53     return 0;
54 }

总结:

(1)模板方法模式是通过把不变行为搬移到超类,取出子类中的重复代码来体现它的优势。

(2)模板方式模式就是提供一个很好的代码复用平台。

(3)当不变的和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现。我们通过模板方法模式把这些行为搬到单一的地方,这样就帮助子类摆脱重复的不变行为的纠缠。

 

  

推荐阅读