//7.模板模式 //ver1 //考試試卷類 class TestPaper { public: void TestQuestion1(){} void TestQuestion2(){} virtual string Answer1() { return ""; } virtual string Answer2() { return ""; } }; class TestPaperA : public TestPaper { public: void TestQuestion1() { TestPaper::TestQuestion1(); //A回答1 Answer1(); } void TestQuestion2() { TestPaper::TestQuestion2(); //A回答2 Answer2(); } string Answer1() { return "A"; } string Answer2() { return "B"; } }; class TestPaperB : public TestPaper { public: void TestQuestion1() { TestPaper::TestQuestion1(); //B回答1 Answer1(); } void TestQuestion2() { TestPaper::TestQuestion2(); //B回答2 Answer2(); } string Answer1() { return "C"; } string Answer2() { return "D"; } }; void main1() { TestPaper * pstuA = new TestPaperA(); pstuA->TestQuestion1(); pstuA->TestQuestion2(); TestPaper * pstuB = new TestPaperB(); pstuB->TestQuestion1(); pstuB->TestQuestion2(); } //模板模式: 定義一個操做中的算法的骨架,而將一些步驟延遲到子類中。 //模板模式使得子類能夠不改變一個算法的結構便可重定義該算法的某些特定步驟。 //模板模式經過把不變行爲搬到超類,去除子類中的重複代碼來體現它的優點。