c++之模板方法模式

模板方法属于属于行为型模式

定义:定义一个操作中的算法骨架,将一些步骤延迟到子类中实现。

优点:使得子类可以不改变一个算法的结构,就可以重定义改算法的某些特定的步骤,将不变的行为移动到父类,用于去除子类中的重复代码,提供了一个很好的代码复用平台。

场景栗子:连接设备的分为TCP和串口连接

代码:

#include <iostream>

using namespace std;

class IConnect
{
public:
	int connectDevice()
	{
		configArgs();
		cout << "配置完毕" << endl;
		if (!connect())
		{
			return -1;
		}
		cout << "连接成功" << endl;
		return 0;
	}
protected:
	virtual void configArgs() = 0;
	virtual bool connect() = 0;

};

class TcpConnect : public IConnect
{
public:
	virtual void configArgs()
	{
		cout << "tcp连接" << endl;
	}
	virtual bool connect()
	{
		cout << "开始tcp连接" << endl;
		return true;
	}
};

class UartConnect : public IConnect
{
public:
	virtual void configArgs()
	{
		cout << "串口连接" << endl;
	}
	virtual bool connect()
	{
		cout << "开始uart连接" << endl;
		return true;
	}
};

//客户端
int main()
{
	IConnect *con = new TcpConnect;
	con->connectDevice();

	cout << "-----------------" << endl;
	con = new UartConnect;
	con->connectDevice();

	if (con)
	{
		delete con;
		con = nullptr;
	}

	return 0;
}

输出效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值