1. 意图
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。Template Method使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
2. 结构
3. 模板模式和策略模式区别
策略模式:定义了一组算法,将每个算法都封装起来,并且使它们之间可以互换。关键点在于每个算法都是过程完整且独立的。
模板方法模式:模板则是将骨架定义好,例如执行的步骤或先后顺序。骨架中的部分在父类中进行实现,而子类的个性化行为则由子类继承再加以实现。
区别的本质就是策略模式是替换了整个流程。而模板模式替换的是固定流程中的一些特定的内容。
4. 例子
//template.h
#pragma once
#include <iostream>
class Template
{
public:
virtual ~Template() = default;
virtual void operate1() = 0;
virtual void operate2() = 0;
void method()
{
operate1();
operate2();
}
};
class Concrete1 : public Template
{
public:
void operate1() { std::cout << "Concrete1 operate1\n"; }
void operate2() { std::cout << "Concrete1 operate2\n"; }
};
class Concrete2 : public Template
{
public:
void operate1() { std::cout << "Concrete2 operate1\n"; }
void operate2() { std::cout << "Concrete2 operate2\n"; }
};
//main.cpp
#include <memory>
#include "template.h"
int main(int argc, char* argv[]) {
std::shared_ptr<Template> tmplt_ptr = std::make_shared<Concrete1>();
tmplt_ptr->method();
tmplt_ptr = std::make_shared<Concrete2>();
tmplt_ptr->method();
return 0;
}
5. 例子2
class DPGamesFramework
{
protected:
virtual bool loadingGame();
virtual bool startGame();
virtual bool playingGame();
virtual bool endGame();
public:
virtual void Run() final;
virtual ~DPGamesFramework();
private:
void errorLog(std::string funcName);
};
void DPGamesFramework::Run()
{
if (!loadingGame())
{
errorLog("loadingGame");
return;
}
if (!startGame())
{
errorLog("startGame");
return;
}
if (!playingGame())
{
errorLog("playingGame");
return;
}
if (!endGame())
{
errorLog("endGame");
return;
}
}
class DPCjGame : public DPGamesFramework
{
public:
bool loadingGame();
bool startGame();
bool playingGame();
bool endGame();
};
int main()
{
DPGamesFramework* cjGame = new DPCjGame();
cjGame->Run();
return 0;
}