面對大量 switch-case 或 if-else if 鏈,程式碼會膨脹、難以維護,且每次新增功能都需修改核心邏輯,違反開放封閉原則。函式映射表將「條件判斷」轉為「查表呼叫」,實現資料驅動設計。
| 策略 | 查詢複雜度 | 記憶體開銷 | 擴展便利性 | 適用場景 |
|---|---|---|---|---|
std::map | O(log N) | 較高(樹節點) | 極佳(動態增刪) | 鍵值稀疏、頻繁增減 |
| 靜態陣列 | O(1) | 低(連續記憶體) | 一般(需維護索引連續性) | 鍵值連續、固定集合 |
| 虛擬函式/策略模式 | O(1) | 中等 | 極佳(多型擴展) | 行為封裝、需狀態 |
本文重點示範前兩種;策略模式留待後續補充。
enum type_func {
type_begin = -1,
type_eat, type_sleep, type_walk, type_run,
type_smile, type_cry, type_jump,
type_max_size
};
class CAnimal {
public:
using ptr_func = int (CAnimal::*)(bool); // 統一簽名:回傳 int、單一 bool 參數
protected:
static std::map s_map;
static ptr_func s_array[type_max_size];
public:
CAnimal() { memset(s_array, 0, sizeof(s_array)); Init(); }
// 具體行為函式
int eat(bool = true) { return printf("eat\n"), 1; }
int sleep(bool = true){ return printf("sleep\n"), 1; }
int walk(bool = true) { return printf("walk\n"), 1; }
int run(bool = true) { return printf("run\n"), 1; }
int smile(bool = true){ return printf("smile\n"), 1; }
int cry(bool = true) { return printf("cry\n"), 1; }
int jump(bool = true) { return printf("jump\n"), 1; }
void Init() {
s_map[type_eat] = &CAnimal::eat;
s_map[type_sleep] = &CAnimal::sleep;
s_map[type_walk] = &CAnimal::walk;
s_map[type_run] = &CAnimal::run;
s_map[type_smile] = &CAnimal::smile;
s_map[type_cry] = &CAnimal::cry;
s_map[type_jump] = &CAnimal::jump;
s_array[type_eat] = &CAnimal::eat;
s_array[type_sleep] = &CAnimal::sleep;
s_array[type_walk] = &CAnimal::walk;
s_array[type_run] = &CAnimal::run;
s_array[type_smile] = &CAnimal::smile;
s_array[type_cry] = &CAnimal::cry;
s_array[type_jump] = &CAnimal::jump;
}
void Process(type_func type) {
switch (type) {
case type_eat: eat(); break;
case type_sleep: sleep(); break;
// ... 其他 case
}
}
void ProcessByMap(int key, bool val) {
auto it = s_map.find(static_cast(key));
if (it != s_map.end() && it->second)
(this->*it->second)(val);
}
void ProcessByArray(int key, bool val) {
if (type_begin < key && key < type_max_size) {
ptr_func pFun = s_array[key];
if (pFun) (this->*pFun)(val);
}
}
int operator[](int key) { // 唯讀呼叫
auto it = s_map.find(static_cast(key));
return (it != s_map.end() && it->second) ? (this->*it->second)(false) : 0;
}
int operator()(int key, bool val) { // 可讀寫呼叫
if (type_begin < key && key < type_max_size) {
ptr_func pFun = s_array[key];
return pFun ? (this->*pFun)(val) : 0;
}
return 0;
}
std::mapCAnimal::s_map; CAnimal::ptr_func CAnimal::s_array[type_max_size];
using ptrFun = void(*)(int); std::mapg_map; ptrFun g_array[type_max_size]; // 初始化 g_map[type_eat] = func_eat; g_array[type_eat] = func_eat;
std::map/unordered_map 靈活。std::function + std::unordered_map 支援 Lambda、仿函式、綁定器。constexpr 建構編譯期映射表,消除執行期初始化開銷。std::variant 或訪問者模式處理多型回傳型別。函式映射表是「資料驅動設計」的經典實踐,善用它能讓分派邏輯與業務邏輯解耦,大幅降低維護成本。