本文通过运用设计模式比没用设计模式的优势在哪?
设计模式主要是要抓住稳定部分和易变部分,文章结尾会指出。
非策略模式
#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...
且不知道未来会不会增加,需要考虑策略模式。
来源:CSDN
作者:waxtear
链接:https://blog.csdn.net/waxtear/article/details/104215744