大话设计模式模板方法模式c++实现

本文深入探讨了设计模式中的模板方法模式,并提供了具体的C++实现示例,帮助理解如何在实际编程中应用该模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板方法模式

其他二十三种设计模式

#include<iostream>

using namespace std;

//模板方法模式
//模板类
class TestPaper{
public:
	void TestQuestion1() {
		cout << "问题1: **" << endl;
		cout << "答案: " << Answer1() << endl;
	}
	void TestQuestion2() {
		cout << "问题2: **" << endl;
		cout << "答案: " << Answer2() << endl;

	}
	void TestQuestion3() {
		cout << "问题3: **" << endl;
		cout << "答案: " << Answer3() << endl;
	}
	void Make() {
		TestQuestion1();
		TestQuestion2();
		TestQuestion3();
	}

protected:
	virtual string Answer1() {
		return "";
	}
	virtual string Answer2() {
		return "";
	}
	virtual string Answer3() {
		return "";
	}
};

class TestPaperA :public TestPaper {
protected:
	virtual string Answer1() {
		return "b";
	}
	virtual string Answer2() {
		return "c";
	}
	virtual string Answer3() {
		return "a";
	}
};

class TestPaperB :public TestPaper {
protected:
	virtual string Answer1() {
		return "c";
	}
	virtual string Answer2() {
		return "a";
	}
	virtual string Answer3() {
		return "a";
	}
};

void test1() {
	cout << "A试卷: " << endl;
	TestPaper* studentA = new TestPaperA();
	studentA->Make();

	cout << "B试卷: " << endl;
	TestPaper* studentB = new TestPaperB();
	studentB->Make();

	delete studentB;
	delete studentA;
}

int main() {
	test1();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值