设计场景:
类与类之间出现很多相同的行为,导致在子类的实现过程中产生重复代码
模板模式特点:
(1)提供了一个很好的代码复用平台;
(2)将子类之间共有的不变的行为搬移到父类,从而体现出去除了子类中重复代码的优势;
(3)当不变的行为和可变的行为在方法的子类实现中混合在一起时,不变的行为就会在子类间重复出现,通过模板方式将这些不变的行为搬移到父类中,帮助子类摆脱重复的不变的行为的纠缠;
代码实现:
(1)框架代码
#pragma once
#include<iostream>
using namespace std;
// 模板类
class Template
{
public:
// 抽象行为放到子类去实现
virtual void primitiveFun() = 0;
// 模板方法 相应的抽象行为形成的逻辑骨架
void templateMethod()
{
primitiveFun();
}
};
#pragma once
#include"template.h"
// 具体类 A
class CONCRETEA : public Template
{
public:
void primitiveFun() override
{
cout << "具体类A 实现方法primitiveFun" << endl;
}
};
#pragma once
#include"template.h"
// 具体类 B
class CONCRETEB : public Template
{
public:
void primitiveFun() override
{
cout << "具体类B 实现方法primitiveFun" << endl;
}
};
#include"template.h"
#include"concrete_A.h"
#include"concrete_B.h"
// 客户端
int main()
{
Template* tp = nullptr;
tp = new CONCRETEA();
tp->templateMethod();
tp = new CONCRETEB();
tp->templateMethod();
system("pause");
return 0;
}
(2)样例实现
描述:针对一套卷子,考察阿强和阿珍最近的知识巩固;
使用模板模式,避免子类间重复出现不变的testQuestion()函数,子类中只需要实现变化的getAnswer()函数即可;
#pragma once
#include<iostream>
#include<string>
using namespace std;
// 模板类
class TESTPAPER
{
public:
// 抽象行为放到子类去实现
virtual string getAnswer() = 0;
// 模板方法 相应的抽象行为形成的逻辑骨架
void testQuestion()
{
cout << "地球是行星还是恒星?(), A.行星 B.恒星" << endl;
cout << "答案:" << getAnswer() << endl;
}
};
#pragma once
#include"testPaper.h"
// 具体类 A
class TESTPAPERA : public TESTPAPER
{
public:
string getAnswer() override
{
return "A";
}
};
#pragma once
#include"testPaper.h"
// 具体类 B
class TESTPAPERB : public TESTPAPER
{
public:
string getAnswer() override
{
return "B";
}
};
#include"testPaper.h"
#include"testPaper_A.h"
#include"testPaper_B.h"
int main()
{
TESTPAPER* tp = nullptr;
tp = new TESTPAPERA();
cout << "阿强试卷的答案:" << tp->getAnswer() << endl;
tp = new TESTPAPERB();
cout << "阿珍试卷的答案:" << tp->getAnswer() << endl;
system("pause");
return 0;
}