1. 程式人生 > >C++重寫《大話設計模式》中模式例項七(模板方法模式)

C++重寫《大話設計模式》中模式例項七(模板方法模式)

其實模板模式的用途比較簡單,我們平時也經常使用。

模板模式就是把子類中相似的部分,儘可能提升到父類中處理,減少重複程式碼。 

程式:

#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;
}

執行結果: