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;
    }





     

  • 相关阅读:
    python-socket1
    python-网络编程
    linux-常用指令3
    linux-vim/编辑器
    linux-常用指令2
    linux-常用指令1
    MySQL 练习题
    33 python 并发编程之IO模型
    32 python 并发编程之协程
    31 python下实现并发编程
  • 原文地址:https://www.cnblogs.com/xj626852095/p/3648194.html
Copyright © 2011-2022 走看看