模板方法属于属于行为型模式
定义:定义一个操作中的算法骨架,将一些步骤延迟到子类中实现。
优点:使得子类可以不改变一个算法的结构,就可以重定义改算法的某些特定的步骤,将不变的行为移动到父类,用于去除子类中的重复代码,提供了一个很好的代码复用平台。
场景栗子:连接设备的分为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;
}
输出效果: