模版模式 主要用于创建软件架构,在父类种定义软件的流程,将在父类中可以实现的流程实现,不能实现的流程,在不同的子类中实现不同的处理流程
有点在于,在父类中实现大部分能够确定的算法和流程,不需要在子类中重复实现,只需在子类中实现父类中不能实现的功能或者子类特有的实现方式。
例如、读取不同类型的文件,可能需要有不同的实具体代码。但基本流程都是一样的,打开文件对话框,选择文件、读取文件等
定义父类:
.h文件
#ifndef PARENT_H
#define PARENT_H
class Parent
{
public:
Parent();
void openFile();
private:
void openDialog();
void selectFile();
virtual void read() const = 0;
};
#endif // PARENT_H
.cpp文件
#include "Parent.h"
#include <QDebug>
Parent::Parent()
{
}
void Parent::openFile()
{
openDialog();
selectFile();
read();
}
void Parent::openDialog()
{
qDebug()<<"open dialog";
}
void Parent::selectFile()
{
qDebug()<<"select file";
}
子类实现:
.h文件
#ifndef CHILD1_H
#define CHILD1_H
#include "Parent.h"
class Child1 : public Parent
{
public:
Child1();
private:
void read() const override;
};
#endif // CHILD1_H
.cpp文件
#include "Child1.h"
#include <QDebug>
Child1::Child1()
{
}
void Child1::read() const
{
qDebug()<<"Child1 open file";
}
main函数中调用
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Child1 chd;
chd.openFile();
return a.exec();
}