本文通過運用設計模式比沒用設計模式的優勢在哪?
設計模式主要是要抓住穩定部分和易變部分,文章結尾會指出。
非模板方法
#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
。
非模板方法是新代碼調用老代碼,模板方法是用老代碼調用新代碼。
類圖: