zoukankan      html  css  js  c++  java
  • 大话设计模式--模板方法模式 TemplateMethod -- C++ 实现

    1. 模板方法模式: 定义一个操作中的算法骨架,而将一些操作延迟到子类,

    模板方法模式使得子类可以不改变一个算法的结构既可以重定义该算法的某些特定步骤。

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

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

    实例:

    template.h template.cpp 模板

    #ifndef TEMPLATE_H
    #define TEMPLATE_H
    
    class Template
    {
    public:
        Template();
        void templateMethod();  //模板方法
        void virtual primitiveOperation1(); //可变操作1
        void virtual primitiveOperation2(); //可变操作2
    };
    
    #endif // TEMPLATE_H
    #include "template.h"
    #include <iostream>
    using namespace std;
    
    Template::Template()
    {
    }
    
    void Template::templateMethod()
    {
        cout << " templateMethod ... ... " << endl;
        primitiveOperation1();
        primitiveOperation2();
    }
    
    void Template::primitiveOperation1()
    {}
    
    void Template::primitiveOperation2()
    {}

    concretetemplate.h concretetemplate.cpp 模板实例,有不同可变操作。。

    #ifndef CONCRETETEMPLATE_H
    #define CONCRETETEMPLATE_H
    
    #include "template.h"
    
    class Concretetemplate : public Template
    {
    public:
        Concretetemplate();
        void  primitiveOperation1();
        void  primitiveOperation2();
    };
    
    #endif // CONCRETETEMPLATE_H
    #include "concretetemplate.h"
    #include <iostream>
    using namespace std;
    
    Concretetemplate::Concretetemplate()
    {
    }
    
    void Concretetemplate::primitiveOperation1()
    {
        cout << "primitiveOperation1" << endl;
    }
    
    void Concretetemplate::primitiveOperation2()
    {
        cout << "primitiveOperation2" << endl;
    }


    main.cpp   可以实例更多的concretetemplate,更多的模板子类

    #include <iostream>
    #include "concretetemplate.h"
    #include "template.h"
    using namespace std;
    
    int main()
    {
        cout << "Template Method!" << endl;
    
        Template *temp = new Concretetemplate();
        temp->templateMethod();
    
        return 0;
    }





     

  • 相关阅读:
    ThinkPHP运算符 与 SQL运算符 对比表
    [Java 8] (6) Lambda与资源管理
    Codeforces Round #275 (Div. 2) C
    HOJ 2245 浮游三角胞(数学啊 )
    [UVALive 6663 Count the Regions] (dfs + 离散化)
    浅解ARC中的 __bridge、__bridge_retained和__bridge_transfer
    SpringMVC: web.xml中声明DispatcherServlet时一定要加入load-on-startup标签
    Unity3d 4.3.4f1执行项目
    更新Windows ActiveX,Ios
    C++11: final与override
  • 原文地址:https://www.cnblogs.com/xj626852095/p/3648194.html
Copyright © 2011-2022 走看看