模板方法模式 Template

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

在基类的算法模板中的子算法,设为虚拟函数,将此虚拟函数放至子类中实现,类似思想可参考另一篇博文中的做法,

http://www.cnblogs.com/xiumukediao/p/4637071.html  多继承时,多个基类中存在型别相同的虚函数,该怎么做?,还是有点类似性的

// TemplateMode.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <IOSTREAM>
using namespace std;


class Abstract{
public:
    virtual void templateoprate(){
        this->operation1();
        this->operation2();
    }    
    virtual void operation1()=0;
    virtual void operation2()=0;
};

class Concreatechild1:public Abstract{
public:
    void operation1(){
        cout<<"child1:operation1"<<endl;
    }
    void operation2(){
        cout<<"child1:operation2"<<endl;
    }
};

class Concreatechild2:public Abstract{
public:
    void operation1(){
        cout<<"child2:operation1"<<endl;
    }
    void operation2(){
        cout<<"child2:operation2"<<endl;
    }
};

int main(int argc, char* argv[])
{
    Abstract * pchild = new Concreatechild1;
    pchild->templateoprate();

    pchild = new Concreatechild2;
    pchild->templateoprate();
    return 0;
}
原文地址:https://www.cnblogs.com/xiumukediao/p/4643164.html