(六)模板方法模式

觉得这个方法在C++中主要就体现在类中的函数是不是virtual函数,当我们需要觉得子类要实现的功能中有一部分是一样的时候,应该在父类中定义为非virtual函数,基本就是这样,就是定义一个操作中的算法骨架,再将某些步骤延迟到子类中去实现(也就是到子类中在实现对应的virtual函数),这个模式不难理解,难得是怎么发现子类的功能有哪些是一样的,发现了后又要怎么在父类中实现,实现的过程中也要记得之前的设计模式原则,简单代码如下:


#include <iostream>
#include <string>

using namespace std;

class TestPaper
{
      public:
                void question_one() 
                {
                     cout << "题目一:" << answer_one() << endl;
                }
                void question_two() 
                {
                     cout << "题目二:" << answer_two() << endl;
                }
                void question_three() 
                {
                     cout << "题目三:" << answer_three() << endl;
                }
      protected:
                virtual string answer_one() {}
                virtual string answer_two() {}
                virtual string answer_three() {}
};

class paperA : public TestPaper
{
      protected:
                string answer_one() { return "A"; }
                string answer_two() { return "B"; }
                string answer_three() { return "C"; }
};

class paperB : public TestPaper
{
      protected:
                string answer_one() { return "C"; }
                string answer_two() { return "A"; }
                string answer_three() { return "A"; }
};

int main()
{
    TestPaper *A = new paperA;
    A->question_one();
    A->question_two();
    A->question_three();
    cout << endl;
    TestPaper *B = new paperB;
    B->question_one();
    B->question_two();
    B->question_three();
    
    getchar();
    getchar();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值