策略模式

淺唱寂寞╮ 提交于 2020-02-07 23:33:34

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

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

非策略模式

#include <iostream>
using namespace std;

//以上班乘坐的交通工具为例

//需要步行和乘公交车去上班
enum TYPE {
    WALK,
    TRANSIT
};
class GoWork {
public:
    void go(TYPE type) {
        if (type == WALK) {
            cout << "走路去上班" << endl;
        } else if (type == TRANSIT ){
            cout << "坐公交去上班" << endl;
        }
    }
};

//现在又增加了地铁的出行方式
enum TYPE2 {
    WALK2,
    TRANSIT2,
    SUBWAY2  //改动部分
};
class GoWork2 {
public:
    void go(TYPE2 type) {
        if (type == WALK2) {
            cout << "走路去上班" << endl;
        } else if (type == TRANSIT2) {
            cout << "坐公交去上班" << endl;
        } else if (type == SUBWAY2) {       //改动部分
            cout << "坐地铁去上班" << endl;
        }
    }
};


int main()
{
    GoWork().go(WALK);
    GoWork2().go(SUBWAY2);
    return 0;
}

策略模式

#include <iostream>
using namespace std;

//以上班乘坐的交通工具为例

//需要步行和乘公交车去上班
class Transport {
public:
    virtual void run() = 0;
    virtual ~Transport() {}
};

class Walk : public Transport {
public:
    void run() override { cout << "步行去上班" << endl; }
};

class Transit : public Transport {
public:
    void run() override { cout << "乘公交去上班" << endl; }
};

class GoWork {
public:
    void go(Transport *transport) {
        transport->run();
    }
};

//现在又增加了地铁的出行方式
class Subway : public Transport {
public:
    void run() override { cout << "乘地铁上班" << endl; }
};

int main()
{
    auto *walk = new Walk();
    GoWork().go(walk);
    delete(walk);
    auto *subway = new Subway();
    GoWork().go(subway);
    delete(subway);
    return 0;
}

策略模式要求:稳定部分:go函数。易变部分:run函数。

没有运用策略模式违背了开闭原则。

如果出现if...else if... else if...且不知道未来会不会增加,需要考虑策略模式。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!