C++重写《大话设计模式》中模式实例七(模板方法模式)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34784043/article/details/82991543

其实模板模式的用途比较简单,我们平时也经常使用。

模板模式就是把子类中相似的部分,尽可能提升到父类中处理,减少重复代码。 

程序:

#include <iostream>
#include <cstdlib>
using namespace std;

//试卷类
class TestPaper {
public:
	virtual ~TestPaper() { }
	void TestQuestion1() {
		cout << "杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁可能是[]" << endl << "a.球磨铸铁 b.马口铁 c.高速合金钢 d.碳素纤维" << endl;
		cout << "答案:" << Answer1() << endl;
	}
	virtual char Answer1() {
		return ' ';
	}
	void TestQuestion2() {
		cout << "杨过、程英、陆无双铲除了情花,造成[]" << endl << "a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生态圈的生态平衡 d.造成该地区的沙漠化" << endl;
		cout << "答案:" << Answer2() << endl;
	}
	virtual char Answer2() {
		return ' ';
	}
	void TestQuestion3() {
		cout << "蓝凤凰致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[]" << endl << "a.阿司匹林 b.牛黄解毒片 c.氟哌酸 d.让他们喝大量的生牛奶 e.以上全不对" << endl;
		cout << "答案:" << Answer3() << endl;
	}
	virtual char Answer3() {
		return ' ';
	}
};

//学生甲抄的试卷
class TestPaperA :public TestPaper {
protected:
	char Answer1() {
		return 'b';
	}
	char Answer2() {
		return 'c';
	}
	char Answer3() {
		return 'a';
	}
};

//学生乙抄的试卷
class TestPaperB :public TestPaper {
protected:
	char Answer1() {
		return 'c';
	}
	char Answer2() {
		return 'a';
	}
	char Answer3() {
		return 'a';
	}
};

int main() {
	cout << "学生甲抄的试卷:" << endl;
	TestPaperA testPaperA;
	TestPaper &studentA = testPaperA;
	studentA.TestQuestion1();
	studentA.TestQuestion2();
	studentA.TestQuestion3();

	TestPaperB testPaperB;
	TestPaper &studentB = testPaperB;
	studentB.TestQuestion1();
	studentB.TestQuestion2();
	studentB.TestQuestion3();

	system("pause");
	return 0;
}

运行结果:

 

猜你喜欢

转载自blog.csdn.net/qq_34784043/article/details/82991543