设计模式--模板方法模式

解释说明:

模板模式也是相当简单的一种模式,而且是比较常用的。模板模式是定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值