開放封閉原則 (OCP):對擴展開放,對修改關閉。新功能透過繼承派生實現,而非修改基類。
#ifndef WIN_32_TEST_H
#define WIN_32_TEST_H
#include <iostream>
#include <ctime>
#include <string>
using std::endl; using std::cout; using std::string;
// 列舉:顏色、形狀
enum Color { red, blue, white, black };
enum Shape { square, circle };
// 抽象基類:封裝通用行為 (顯示時間)
class Clock {
public:
inline string GetTime() { // 通用邏輯放基類
time_t now; time(&now);
tm *NT = localtime(&now);
char *pTemp = new char[24];
string sHour = itoa(NT->tm_hour, pTemp, 10);
memset(pTemp, 0, 24);
string sMin = itoa(NT->tm_min, pTemp, 10);
memset(pTemp, 0, 24);
string sSec = itoa(NT->tm_sec, pTemp, 10);
delete[] pTemp;
return sHour + ":" + sMin + ":" + sSec;
}
virtual int GetColor() = 0; // 純虛函數:強制派生類實作
private:
time_t now; tm *NT;
};
// 派生:掛鐘
class WallClock : public Clock {
public:
int GetColor() override { return red; }
int GetShape() { return square; } // 派生類專屬擴展
};
// 派生:鬧鐘
class AlarmClock : public Clock {
public:
int GetColor() override { return black; }
int GetShape() { return circle; }
};
// 二次派生:功能增強鬧鐘 (從 AlarmClock 派生,非 Clock)
class AlarmClockExtend : public AlarmClock {
public:
void Alarm() { cout << "Alarm" << endl; } // 新增鬧鈴功能
};
#endif
| 決策 | 做法 | 效益 |
|---|---|---|
| 通用邏輯下沉 | GetTime() 放基類 | 避免重複、單一維護點 |
| 差異化抽象 | GetColor() 純虛函數 | 強制契約、多型調用 |
| 專屬功能下放 | GetShape() 只在派生類 | 基類不汙染、介面乾淨 |
| 新功能二次派生 | AlarmClockExtend : AlarmClock | 不動基類、不動現有派生類 |
WorldClock:繼承 Clock、實作 GetColor()、加 GetTimezone()SmartWatch:繼承 AlarmClockExtend、加 HeartRate()範例中 new char[24] / delete[] 手動管理,現代 C++ 建議:
std::string / std::ostringstream 避免裸指標std::unique_ptr 管理動態陣列