zoukankan      html  css  js  c++  java
  • C++设计模式之-模板模式

    模板方法模式

    在GOF的《设计模式:可复用面向对象软件的基础》一书中对模板方法模式是这样说的:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。TemplateMethod使得子类可以不改变一个算法的接口即可重定义改算法的某些特定步骤。

    UML类图

    代码实现:

      1 // Template.cpp : 定义控制台应用程序的入口点。
      2 //
      3 
      4 #include "stdafx.h"
      5 #include <iostream>
      6 #include<string>
      7 using namespace std;
      8 
      9 
     10 class AbstractClass
     11 
     12 {
     13 
     14 public:
     15 
     16     void TemplateMethod()
     17 
     18     {
     19 
     20         PrimitiveOperation1();
     21 
     22         cout<<"TemplateMethod"<<endl;
     23 
     24         PrimitiveOperation2();
     25 
     26     }
     27 
     28 
     29 
     30 protected:
     31 
     32     virtual void PrimitiveOperation1()
     33 
     34     {
     35 
     36         cout<<"Default Operation1"<<endl;
     37 
     38     }
     39 
     40 
     41 
     42     virtual void PrimitiveOperation2()
     43 
     44     {
     45 
     46         cout<<"Default Operation2"<<endl;
     47 
     48     }
     49 
     50 };
     51 
     52 
     53 
     54 class ConcreteClassA : public AbstractClass
     55 
     56 {
     57 
     58 protected:
     59 
     60     virtual void PrimitiveOperation1()
     61 
     62     {
     63 
     64         cout<<"ConcreteA Operation1"<<endl;
     65 
     66     }
     67 
     68 
     69 
     70     virtual void PrimitiveOperation2()
     71 
     72     {
     73 
     74         cout<<"ConcreteA Operation2"<<endl;
     75 
     76     }
     77 
     78 };
     79 
     80 
     81 
     82 class ConcreteClassB : public AbstractClass
     83 
     84 {
     85 
     86 protected:
     87 
     88     virtual void PrimitiveOperation1()
     89 
     90     {
     91 
     92         cout<<"ConcreteB Operation1"<<endl;
     93 
     94     }
     95 
     96 
     97 
     98     virtual void PrimitiveOperation2()
     99 
    100     {
    101 
    102         cout<<"ConcreteB Operation2"<<endl;
    103 
    104     }
    105 
    106 };
    107 int _tmain(int argc, _TCHAR* argv[])
    108 {
    109 
    110      AbstractClass *pAbstractA = new ConcreteClassA;
    111 
    112      pAbstractA->TemplateMethod();
    113 
    114  
    115 
    116      AbstractClass *pAbstractB = new ConcreteClassB;
    117 
    118      pAbstractB->TemplateMethod();
    119 
    120  
    121 
    122      if (pAbstractA) delete pAbstractA;
    123 
    124      if (pAbstractB) delete pAbstractB;
    125 
    126     system("pause");
    127     return 0;
    128 }

  • 相关阅读:
    【MFC】对话框自带滚动条的使用
    【MFC】MFC DLEdit 设计属于自己的编辑框_鼠标悬停
    【MFC】MoveWindow();函数使用详解
    【MFC】SetWindowPos函数使用详解
    模板 key+1
    lazyload 分页加载
    缓慢显示隐藏
    js计算日期的前几天的日期
    判断子元素(or属性)是否存在
    动态加载的数据,hover效果
  • 原文地址:https://www.cnblogs.com/wxmwanggood/p/9274589.html
Copyright © 2011-2022 走看看