设计模式学习(十二) 模板模式 Template

1.模板模式的定义与类图

从这里开始进入行为型模式阶段,行为型模式主要是指用来对类或对象怎样交互和怎样分配职责进行描述。

模板模式即指在抽象类中统一操作步骤,并规定好接口,其子类实现接口,从而实现将各个具体的子类和操作步骤解耦合。通俗点说,就是模板类定义了一个/多个确定接口逻辑与步骤的函数,同时定义多个需要重载的接口,子类负责重载这些接口即可,具体的逻辑操作均有基类的逻辑函数来确定,客户端调用时也是直接调用具体子类new出对象,而函数仍是使用基类的逻辑函数。
其类图如下:
模板模式类图
类图中,TemplateMethod即为所述的逻辑函数,而Method1和Method2即为接口函数。

2.模板模式的代码实现

本例中使用MakeBicycle作为基类,其中定义了makeWheel,makeBrake和makeCushion三个接口函数,并定义逻辑函数makebicycle,用于实现接口函数的执行逻辑与顺序。两个派生类为Make_NormalBicycle和Make_GreatBicycle,表示两种不同的自行车创造过程。
具体代码如下:

#include <iostream>
#include <string>
using namespace std;

class MakeBicycle
{
public:
	void makebicycle()   //模板模式的特点就是这个函数,定义了执行的规则与逻辑
	{
		makeWheel();
		makeBrake();
		makeCushion();
	}
protected:
	virtual void makeWheel() = 0;
	virtual void makeBrake() = 0;
	virtual void makeCushion() = 0;
};

class Make_NormalBicycle : public MakeBicycle
{
public:
	void makeWheel()
	{
		cout << "Make the normal bicycle's wheel!" << endl;
	}
	void makeBrake()
	{
		cout << "Make the normal bicycle's brake!" << endl;
	}
	void makeCushion()
	{
		cout << "Make the normal bicycle's cushion!" << endl;
	}
};

class Make_GreatBicycle : public MakeBicycle
{
public:
	void makeWheel()
	{
		cout << "Make the great bicycle's wheel!" << endl;
	}
	void makeBrake()
	{
		cout << "Make the great bicycle's brake!" << endl;
	}
	void makeCushion()
	{
		cout << "Make the great bicycle's cushion!" << endl;
	}
};

int main()
{
	MakeBicycle* normalbicycle = new Make_NormalBicycle;
	normalbicycle->makebicycle();
	MakeBicycle* greatbicycle = new Make_GreatBicycle;
	greatbicycle->makebicycle();

	delete normalbicycle;
	delete greatbicycle;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

方寸间沧海桑田

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值