解释说明:
模板模式也是相当简单的一种模式,而且是比较常用的。模板模式是定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。TemplateMethod使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
说明:在CHummerModel声明Start、Engineboom、Alarm、Stop虚函数,由派生类实现。基类的Run负责组织逻辑,分别调用这几个派生类实现的函数。
注意:基类中的Run应该禁止派生类覆盖。
参考链接:https://www.cnblogs.com/wanggary/category/294620.html
https://blog.csdn.net/phiall/article/details/52199659
#include <iostream>
using namespace std;
class CHummerModel
{
public:
CHummerModel(){}
~CHummerModel(){}
void Run()
{
//先发动汽车
Start();
//引擎开始轰鸣
EngineBoom();
//然后就开始跑了,跑的过程中遇到一条狗挡路就按喇叭
if (IsAlarm())
Alarm();
//到达目的地就停车
Stop();
}
protected:
virtual void Start() = 0;
virtual void Stop() = 0;
virtual void Alarm() = 0;
virtual void EngineBoom() = 0;
virtual bool IsAlarm()
{
//钩子方法,默认喇叭是会响的
return true;
}
};
class CHummerModel1 :public CHummerModel
{
public:
CHummerModel1()
{
m_isAlarm = true;
}
~CHummerModel1(){}
void SetAlarm(bool tag)
{
this->m_isAlarm = tag;
}
void Start()
{
cout << "悍马H1发动..." << endl;
}
void Stop()
{
cout << "悍马H1停车..." << endl;
}
void Alarm()
{
cout << "悍马H1鸣笛" << endl;
}
void EngineBoom()
{
cout << "悍马H1引擎声音是这样...." << endl;
}
bool IsAlarm()
{
return this->m_isAlarm;
}
private:
bool m_isAlarm;
};
class CHummerModel2 :public CHummerModel
{
public:
CHummerModel2(){}
~CHummerModel2(){}
void Start()
{
cout << "悍马H2发动..." << endl;
}
void Stop()
{
cout << "悍马H2停车..." << endl;
}
void Alarm()
{
cout << "悍马H2鸣笛" << endl;
}
void EngineBoom()
{
cout << "悍马H2引擎声音是这样...." << endl;
}
bool IsAlarm()
{
return false;
}
};
int main()
{
//客户开着H1型号,出去遛弯了
CHummerModel* ph1 = new CHummerModel1();
ph1->Run();
delete ph1;
cout << endl << endl;
//客户开着H2型号,出去玩耍了
CHummerModel* ph2 = new CHummerModel2();
ph2->Run();
delete ph2;
cout << endl << endl;
//客户开着H1型号,出去遛弯了,并且不让喇叭响
CHummerModel1* ph11 = new CHummerModel1();
ph11->SetAlarm(false);
ph11->Run();
delete ph11;
cout << endl << endl;
return 0;
}