雖然現代開發多用 Java、Python、JavaScript,但 C 語言的指針機制依然是理解底層運行機制、實現高性能系統的關鍵。本文通過一個任務/執行器回調框架,展示如何純用 C 指針實現「封裝」「多態」「接口解耦」等面向對象核心思想。
taskName,可執行 execute(),具體邏輯由外部注入Task.execute(),支持 setTask()、begin()、cancel()
#ifndef _ITASK_H
#define _ITASK_H
typedef struct Task {
struct Task *_this; // 指向自身實例,實現封裝關鍵
char *taskName; // 任務名稱
void (*execute)(); // 函數指針:具體執行邏輯
} Task;
void execute(); // 內部回調入口
#endif
#ifndef _IEXECUTOR_H
#define _IEXECUTOR_H
#include "ITask.h"
typedef struct Executor {
struct Executor *_this; // 指向自身
Task *task; // 當前綁定的任務
char *(*setTask)(Task *task); // 設置任務
void (*begin)(); // 開始執行
void (*cancel)(); // 取消執行
} Executor;
char *setTask(Task *task);
void begin();
void cancel();
#endif
Task *TaskConstruction(char *name, void (*execute)()) {
Task *task = (Task*)malloc(sizeof(Task));
task->taskName = name;
task->execute = execute; // 注入具體執行函數
task->_this = task; // _this 指向自身
return task;
}
_this 是封裝的核心:內部方法 execute() 通過 task->_this->execute() 間接調用,實現「實例方法」語義。
Executor *ExecutorConstruction() {
Executor *executor = (Executor*)malloc(sizeof(Executor));
executor->begin = begin; // 註冊內部 begin 實現
executor->cancel = cancel;
executor->setTask = setTask;
executor->_this = executor;
return executor;
}
// setTask:綁定任務到執行器
char *setTask(Task *task) {
executor->_this->task = task;
}
// begin:觸發任務執行
void begin() {
printf("task : [%s] is ready to run\n", executor->_this->task->taskName);
executor->_this->task->execute(); // 回調任務的 execute
}
// cancel:佔位,可擴展為線程取消
void cancel() {
printf("cancel is invoked here\n");
}
// 任務 1:數學運算
void run() {
float a = 1.2, b = 2.3;
printf("[a = %f, b = %f]\n", a, b);
printf("[(a + b) * (a - b) = %f]\n", (a+b)*(a-b));
}
// 任務 2:純打印
void run2() {
printf("another type of execute, just print out some information\n");
}
// main:面向對象風格調用
int main() {
Task *t1 = TaskConstruction("Task1", run);
Executor *exe = ExecutorConstruction();
exe->setTask(t1);
exe->begin();
exe->cancel();
Task *t2 = TaskConstruction("Task2", run2);
exe->setTask(t2);
exe->begin();
exe->cancel();
return 0;
}
task : [Task1] is ready to run [a = 1.200000, b = 2.300000] [(a + b) * (a - b) = -3.850000] cancel is invoked here task : [Task2] is ready to run another type of execute, just print out some information cancel is invoked here
this 指針,讓結構體擁有「方法」new,手動 free 對應析構面向對象本質是思想抽象,與語言無關。C 語言通過指針、結構體、函數指針完全可以實現封裝、繼承、多態。本例展示的 Task/Executor 模式 正是策略模式的 C 語言原生實現。理解這套機制,不僅能寫出可擴展的 C 代碼,更能深入理解 C++、Java 等語言底層的對象模型實現原理。