本文通过运用设计模式比没用设计模式的优势在哪?
设计模式主要是要抓住稳定部分和易变部分,文章结尾会指出。
非模板方法
#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
。
非模板方法是新代码调用老代码,模板方法是用老代码调用新代码。
类图: