c++模板方法

本文通过运用设计模式比没用设计模式的优势在哪?

设计模式主要是要抓住稳定部分和易变部分,文章结尾会指出。

非模板方法
#include <iostream>
using namespace std;

//以去上班为例

//去上班必要过程,前人已经写好的类。
class GoWork {
public:
    void wakeup() { cout << "起床" << endl; }
    void eat() { cout << "吃早餐" << endl; }
    void clock() { cout << "到公司打卡" << endl; }
};

//现在需要我们完成(起床,吃早餐,然后坐地铁去上班的打卡)
class GoWorkBySubway : public GoWork {
public:
    void go() {
        wakeup();
        eat();
        subway();
        clock();
    }
private:
    void subway() { cout << "坐地铁去公司" << endl; }
};

//然后过了一段时间,又需要(起床,没时间迟早餐,然后直接打车去上班打卡)
class GoWorkByTaxi : public GoWork {
public:
    void go() {
        wakeup();
        taxi();
        clock();
    }
private:
    void taxi() { cout << "打车去公司" << endl; }
};

int main()
{
    GoWorkBySubway().go();
    GoWorkByTaxi().go();
    return 0;
}
模板方法
#include <iostream>
using namespace std;

//还以去上班为例

//去上班必要过程,前人已经写好的类。
class GoWork {
public:
    void go() {
        wakeup();
        if (timeOK()) {
            eat();
        }
        transport();
        clock();
    }
    void wakeup() { cout << "起床" << endl; }
    void eat() { cout << "吃早餐" << endl; }
    void clock() { cout << "到公司打卡" << endl; }
protected:
    virtual bool timeOK() = 0;
    virtual void transport() = 0;
};

//现在需要我们完成(起床,吃早餐,然后坐地铁去上班的打卡)
class GoWorkBySubway : public GoWork {
protected:
    bool timeOK() override { return true; }
    void transport() override { cout << "坐地铁去上班" << endl; }
};

//然后过了一段时间,又需要(起床,没时间迟早餐,然后直接打车去上班打卡)
class GoWorkByTaxi : public GoWork {
protected:
    bool timeOK() override { return false; }
    void transport() override { cout << "打车去公司" << endl; }
};

int main()
{
    GoWorkBySubway().go();
    GoWorkByTaxi().go();
    return 0;
}

模板方法要求:稳定部分:go函数,wakeup/eat/clock。易变部分是:timeOK/transport
非模板方法是新代码调用老代码,模板方法是用老代码调用新代码。

类图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值