模板方法模式:
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
模板方法的一般实现:
- //AbstractClass是一个抽象类,其实也就是一个抽象模板,并且实现了一个模板方法。
//这个模板方法一般是一个具体方法,它给出了一个顶级逻辑的骨架,而逻辑的组成步
//骤在相应的抽象操作中,推迟到了子类中实现,顶级逻辑也可能调用一些具体方法。 - class AbstractClass
- {
- public:
- void TemplateMethond()
- {
- PrimitiveOperation1();
- PrimitiveOperation2();
- }
- protecetd:
- virtual void PrimitiveOperation1() = 0;
- virtual void PrimitiveOperation2() = 0;
- };
- class ConcreteClassA : public AbstractClass
- {
- public:
- virtual void PrimitiveOperation1()
- {
- cout << "具体类A方法实现1" << endl;
- }
- virtual void PrimitiveOperation2()
- {
- cout << "具体类A方法实现2" << endl;
- }
- };
- class ConcreteClassB : public AbstractClass
- {
- public:
- virtual void PrimitiveOperation1()
- {
- cout << "具体类B方法实现1" << endl;
- }
- virtual void PrimitiveOperation2()
- {
- cout << "具体类B方法实现2" << endl;
- }
- };
- int main(int argc, char* argv[])
- {
- AbstractClass * abs1 = new ConcreteClassA();
- abs1->TemplateMethond();
- AbstractClass * abs2 = new ConcreteClassB();
- abs2->TemplateMethond();
- return 0;
- }
模板方法模式是通过把不变行为转移到基类,去除子类中的重复代码来体现它的优势。模板方法模式就是提供了一个很好的代码复用平台。当不变的和可变的行为在子类的方法中混合出项时,不变的行为就会在子类中重复出现,我们通过模板方法模式把这些行为搬移到单一的地方,这样就帮助子类摆脱重复的部分。
模板方法模式的具体实现方法
金庸小说考题试卷
- class TestPaper
- {
- public:
- void TestQuestion1()
- {
- cout << " 杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁可能是[ ] a.球磨铸铁 b.马口铁 c.高速合金钢 d.碳素纤维 " << endl;
- cout << "答案:" << Answer1() << endl;
- }
- void TestQuestion2()
- {
- cout << " 杨过、程英、陆无双铲除了情花,造成[ ] a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化 " << endl;
- cout << "答案:" << Answer2() << endl;
- }
- void TestQuestion3()
- {
- cout << " 蓝凤凰的致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[ ] a.阿司匹林 b.牛黄解毒片 c.氟哌酸 d.让他们喝大量的生牛奶 e.以上全不对 " << endl;
- cout << "答案:" << Answer3() << endl;
- }
- 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
- {
- virtual string Answer1()
- {
- return "c";
- }
- virtual string Answer2()
- {
- return "a";
- }
- virtual string Answer3()
- {
- return "a";
- }
- };
- int main()
- {
- cout << "学生甲抄的试卷:" << endl;
- TestPaper * studentA = new TestPaperA();
- studentA->TestQuestion1();
- studentA->TestQuestion2();
- studentA->TestQuestion3();
- cout << "学生乙抄的试卷:" << endl;
- TestPaper * studentB = new TestPaperB();
- studentB->TestQuestion1();
- studentB->TestQuestion2();
- studentB->TestQuestion3();
- return 0;
- }