模板方法(template method)c++版本

来源:互联网 发布:淘宝一元起拍在哪里 编辑:程序博客网 时间:2024/06/03 21:14

大话设计模式中的template method c++版本

/* * template_method.cpp * *  Created on: Jul 24, 2017 *      Author: clh01s@163.com *      模板方法 */#include <iostream>#include <string>#include <unistd.h>using namespace std;//模板类(题目)class TestPaper{public:    virtual ~TestPaper(){};    //答案的纯虚函数,表示每个人的答案都是不一样的    virtual string AnswerOne()=0;    virtual string AnswerTwo()=0;    virtual string AnswerThree()=0;    void TestQuestionOne()    {        cout<<"121+2 = [] a.122 b.123 c.124"<<endl;        cout<<"答案:"<<AnswerOne()<<endl;    }    void TestQuestionTwo()    {        cout<<"33*2 = [] a.33 b.66 c.99"<<endl;        cout<<"答案:"<<AnswerTwo()<<endl;    }    void TestQuestionThree()    {        cout<<"36/3 = [] a.13 b.14 c.12"<<endl;        cout<<"答案:"<<AnswerThree()<<endl;    }};//学生继承试卷class StudentATest:public TestPaper{public:    char a[1024*1024*1024];    struct c v[1024];    ~StudentATest(){}    string AnswerOne() override    {        return "b";    }    string AnswerTwo() override    {        return "b";    }    string AnswerThree() override    {        return "c";    }};class StudentBTest:public TestPaper{public:    string AnswerOne() override    {        return "c";    }    string AnswerTwo() override    {        return "a";    }    string AnswerThree() override    {        return "c";    }};int main(){    cout<<"学生A的答案:"<<endl;    //将子类变量的声明改成了父类,利用多态实现复用    TestPaper *studentA = new StudentATest();    studentA->TestQuestionOne();    studentA->TestQuestionTwo();    studentA->TestQuestionThree();    cout<<"学生B的答案:"<<endl;    TestPaper *studentB = new StudentBTest();    studentB->TestQuestionOne();    studentB->TestQuestionTwo();    studentB->TestQuestionThree();    //释放资源    delete studentA;    delete studentB;    return 0;}

程序输出:
学生A的答案:
121+2 = [] a.122 b.123 c.124
答案:b
33*2 = [] a.33 b.66 c.99
答案:b
36/3 = [] a.13 b.14 c.12
答案:c
学生B的答案:
121+2 = [] a.122 b.123 c.124
答案:c
33*2 = [] a.33 b.66 c.99
答案:a
36/3 = [] a.13 b.14 c.12
答案:c

模板模式适用环境(摘录子《设计模式》):
1.一次性实现一个算法的不变的部分,并将可变的行为留给子类来实现.
2.各子类中公共的行为应被提取出来并集中到一个公共父类中以避免代码重复.3
3.控制子类扩展.模板方法只在特定点调用”hook”操作,这样就只允许在这些点进行扩展.(hook:表示可以在特定位置重定义.需要区分那些是hook操作(可以重定义)那些是抽象操作(必须重定义))
转载请注明源地址:http://blog.csdn.net/clh01s