案例:打开PPT,World,Excel文件都要经历搜索文件->选择文件->检查文件名称->读取文件。除了具体读取文件方式不同,其余步骤基本相同
模板方法模式
模板方法模式定义(Template Method Patter)
模板方法模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤
模板方法模式结构
- AbstractClass(基类) 基类中定义或声明了一系列基本操作method, 这些操作是具体或者抽象的,每一个操作都对应算法的一个步骤,在其派生类中可以重定义。基类中定义了一个模板方法,它规定了算法的流程框架,模板方法由基类定义或声明的一系列基本操作按照一定流程实现。
- ConcreteClass(派生类) 实现在基类中声明的抽象的方法,也可以覆盖在基类中已经实现的方法
模板方法示例
https://gitee.com/NiMiKiss/design-pattern.git
#ifndef _TEMPLATEMETHOD_PATTERN_
#define _TEMPLATEMETHOD_PATTERN_
#include<iostream>
class CDocument
{
public:
void SearchFile() { std::cout << "搜索文件" << std::endl; }
void SelectFile() { std::cout << "选择文件" << std::endl; }
void CheckFileName() { std::cout << "检查文件名称" << std::endl; }
virtual void Serialize() = 0;
void OnFileOpen()
{
SearchFile();
SelectFile();
CheckFileName();
Serialize();
}
};
class CPPTDocument :public CDocument
{
public:
void Serialize()
{
std::cout << "打开PPT文件" << std::endl;
}
};
class CWorldDocument :public CDocument
{
public:
void Serialize()
{
std::cout << "打开World文件" << std::endl;
}
};
class CExcelDocument :public CDocument
{
public:
void Serialize()
{
std::cout << "打开Excel文件" << std::endl;
}
};
#endif // !_TEMPLATEMETHOD_PATTERN_
客户端调用
#include "Template_Method_Pattern.h"
#include<iostream>
int main()
{
auto spCPPTDocument = std::shared_ptr<CPPTDocument>(new CPPTDocument());
spCPPTDocument->OnFileOpen();
auto spCWorldDocument = std::shared_ptr<CWorldDocument>(new CWorldDocument());
spCWorldDocument->OnFileOpen();
auto spCExcelDocument = std::shared_ptr<CExcelDocument>(new CExcelDocument());
spCExcelDocument->OnFileOpen();
return EXIT_SUCCESS;
}