template模式
2017-11-16 本文已影响0人
老练子丶2017
子类重载继承template类实现,不继承template类接口,将虚函数放入protected里面
与strategy不同的是模板是继承,strategy是组合(委托)实现
template.h
#ifndef _TEMPLATE_H
#define _TEMPLATE_H
#include <iostream>
using namespace std;
class Template
{
public:
Template() {};
virtual ~Template() {};
void method() {
print();
}
protected:
virtual void print()=0;
};
class Method1 : public Template
{
public:
~Method1() {};
protected:
void print() {
cout << "method1" << endl;
}
};
class Method2 : public Template
{
public:
~Method2() {};
protected:
void print() {
cout << "method2" << endl;
}
};
#endif // _TEMPLATE_H
template.cpp:
#include "template.h"
int main()
{
Template* t1 = new Method1;
Template* t2 = new Method2;
t1->method();
t2->method();
return 0;
}
编译:make template