c++template method模板方法

模板方法一般在类库里面比较常见,类库里把实现某一功能需要的各个步骤逻辑实现好,调用者只需要按照需要重新修改某几步。框架是相对稳定的,变化隔离在客户程序。
例如实现某一功能逻辑如下
step1()
step2()
if (step()3)
setp4()
setp5()
step2和step4不同用户有不同实现,其他步骤固定
将上述逻辑用模板方法实现

template_method_lib.h

#ifndef _TEMPLATE_METHOD_LIB_H
#define _TEMPLATE_METHOD_LIB_H
using  namespace std;

class lib{
public:
    void doTask();
protected:
    virtual bool step3() = 0;
    virtual void step4() = 0;
private:
    void step1();
    void step2();
    void step5();
};
#endif

template_method_lib.cpp

#include "template_method_lib.h"
#include <iostream>


void lib::step1(){
    cout<<"step1"<<endl;
}

void lib::step2(){
    cout<<"step2"<<endl;
}

void lib::step5(){
    cout<<"step5"<<endl;
}

void lib::doTask(){
    step1();
    step2();
    if(step3()){
        step4();
    }
    step5();
}

template_method_app.h

#ifndef _TEMPLATE_METHOD_APP_H
#define _TEMPLATE_METHOD_APP_H
#include "template_method_lib.h"
using  namespace std;

class app :public lib{
public:
    app(int id):m_id(id){}
protected:
    virtual bool step3()override;
    virtual void step4()override;
private:
int m_id;
};
#endif

template_method_app.cpp

#include "template_method_app.h"
#include <iostream>

bool app::step3(){
    cout<<"step3"<<endl;
    return m_id%2 == 0;
}

void app::step4(){
    cout<<"step4"<<endl;
}

main.cpp

#include "template_method_app.h"


int main(){
    app cApp(2);
    cApp.doTask();
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值