您的位置:首页 > 其它

模板方法模式 Template

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

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

/article/5875159.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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: