模板方法模式(TemplateMethod Pattern)
基本概念:
模板方法模式从概念上讲,还是很容易理解的。需要执行两个任务,其中两个任务间既有共同的部分,又有不同的部分。那我们可以将两个任务重相同的部分提取出来,计划好流程,然后在后续执行任务过程中着重不同的部分。
比较抽象,但是好记得一句话(四个字)概括:分离异同。
具体应用举例:
在笔者实际工作中,经常使用索尼的相机进行前端的采集设备。同样是索尼品牌相继,但是不同类型的相机既有相同的操作,也有不同的操作。本次只针对初始化操作这一部分进行举例。
暂且给两款相机分别取代号x30和x30u, 其中x30在初始化的时候的基本流程是:发送connect code1 ---> 发送connect code2 ---> 设置时间格式 ---> 设置工作模式 ---> 设置初始化zoom position ---> 设置liveview分辨率 ---> 进入命令等待状态。 而对于x30u来说,不需要发送connect code2,工作模式是默认的,不需要设置,起始zoom position为0,不需要设置。在这种两者初始化既有相同部分,又有不同不分的情况下,可以使用模板方法模式来进行代码上的优化。
老规矩,直接上代码:
#include <QCoreApplication>
#include <iostream>
#include <stdlib.h>
using namespace std;
class SonyCameraInit
{
public:
void SendConnectCode1()
{
cout << "SendConnectCode1" << endl;
}
virtual void SendConnectCode2() = 0;
void SetTimeFormat()
{
cout << "SetTimeFormat" << endl;
}
virtual void SetOperationMode() = 0;
virtual void InitZoomPosition() = 0;
void SetLiveviewResolution()
{
cout << "SetLiveviewResolution" << endl;
}
void WaitCommand()
{
cout << "WaitCommand..." << endl;
}
void Init()
{
SendConnectCode1();
SendConnectCode2();
SetTimeFormat();
SetOperationMode();
InitZoomPosition();
SetLiveviewResolution();
WaitCommand();
}
};
class Qx30Init: public SonyCameraInit
{
public:
virtual void SendConnectCode2()
{
cout << "SendConnectCode2 for qx30" << endl;
}
virtual void SetOperationMode()
{
cout << "SetOperationMode for qx30" << endl;
}
virtual void InitZoomPosition()
{
cout << "InitZoomPosition for qx30" << endl;
}
};
class Qx30uInit: public SonyCameraInit
{
virtual void SendConnectCode2()
{
cout << "Do not need SendConnectCode2 for qx30u" << endl;
}
virtual void SetOperationMode()
{
cout << "Do not need SetOperationMode for qx30u" << endl;
}
virtual void InitZoomPosition()
{
cout << "Do not need InitZoomPosition for qx30u" << endl;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
SonyCameraInit* Qx30_init = new Qx30Init();
Qx30_init->Init();
cout<<"**********"<<endl;
SonyCameraInit* Qx30u_init = new Qx30uInit();
Qx30u_init->Init();
return a.exec();
}
看结果:

本文通过对比分析索尼相机初始化过程中的共性和个性操作,详细介绍了模板方法模式的应用。以x30和x30u两款相机为例,展示了如何通过模板方法模式优化代码结构,实现相同流程的灵活扩展。
&spm=1001.2101.3001.5002&articleId=81746140&d=1&t=3&u=b3956940bc7c43568c05dfcd3610b7ad)
124

被折叠的 条评论
为什么被折叠?



