【7】模板模式

设计场景:

类与类之间出现很多相同的行为,导致在子类的实现过程中产生重复代码


模板模式特点:

(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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值