数据驱动编程思想
约 381 字大约 1 分钟
2026-08-03
数据驱动编程思想
1.表驱动方法
#include <stdio.h>
#include <string.h>
// 传统方式 - 大量if-else
void handle_command_traditional(char* cmd) {
if (strcmp(cmd, "start") == 0) {
printf("Starting service...\n");
} else if (strcmp(cmd, "stop") == 0) {
printf("Stopping service...\n");
} else if (strcmp(cmd, "restart") == 0) {
printf("Restarting service...\n");
} else if (strcmp(cmd, "status") == 0) {
printf("Service status: running\n");
} else {
printf("Unknown command\n");
}
}
// 数据驱动方式 - 函数指针表
typedef struct {
char* command;
void (*handler)(void);
} command_entry_t;
void start_handler() { printf("Starting service...\n"); }
void stop_handler() { printf("Stopping service...\n"); }
void restart_handler() { printf("Restarting service...\n"); }
void status_handler() { printf("Service status: running\n"); }
command_entry_t command_table[] = {
{"start", start_handler},
{"stop", stop_handler},
{"restart", restart_handler},
{"status", status_handler},
{NULL, NULL}
};
void handle_command_driven(char* cmd) {
for (int i = 0; command_table[i].command != NULL; i++) {
if (strcmp(cmd, command_table[i].command) == 0) {
command_table[i].handler();
return;
}
}
printf("Unknown command\n");
}2.配置驱动的状态机
#include <stdio.h>
typedef enum {
STATE_IDLE,
STATE_RUNNING,
STATE_PAUSED,
STATE_STOPPED
} state_t;
typedef enum {
EVENT_START,
EVENT_PAUSE,
EVENT_RESUME,
EVENT_STOP
} event_t;
// 状态转换表
int state_transition[4][4] = {
// START PAUSE RESUME STOP
{STATE_RUNNING, -1, -1, STATE_STOPPED}, // IDLE
{-1, STATE_PAUSED, -1, STATE_STOPPED}, // RUNNING
{-1, -1, STATE_RUNNING, STATE_STOPPED}, // PAUSED
{STATE_RUNNING, -1, -1, -1} // STOPPED
};
state_t current_state = STATE_IDLE;
void process_event(event_t event) {
int next_state = state_transition[current_state][event];
if (next_state != -1) {
printf("State changed from %d to %d\n", current_state, next_state);
current_state = next_state;
} else {
printf("Invalid transition\n");
}
}3.数据驱动的计算器
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char operator;
double (*operation)(double, double);
} operation_t;
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) {
return b != 0 ? a / b : 0;
}
operation_t operations[] = {
{'+', add},
{'-', subtract},
{'*', multiply},
{'/', divide},
{'\0', NULL}
};
double calculate(double a, double b, char op) {
for (int i = 0; operations[i].operator != '\0'; i++) {
if (operations[i].operator == op) {
return operations[i].operation(a, b);
}
}
printf("Unknown operator\n");
return 0;
}