栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

模板模式&

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

模板模式&

设计场景:

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


模板模式特点:

(1)提供了一个很好的代码复用平台;
(2)将子类之间共有的不变的行为搬移到父类,从而体现出去除了子类中重复代码的优势;
(3)当不变的行为和可变的行为在方法的子类实现中混合在一起时,不变的行为就会在子类间重复出现,通过模板方式将这些不变的行为搬移到父类中,帮助子类摆脱重复的不变的行为的纠缠;


代码实现:

(1)框架代码

#pragma once
#include
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
#include
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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690834.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号