突然想做做一些嵌入式设计模式方面的小例子,希望大家多抛砖头!
模式一:state 应用范围:一些带有状态转换的工业控制软件中,如洗衣机,门禁 代码示例: enum STATE { LOCK_STATE = 0, UNLOCK_STATE = 1, };
enum EVENT_CODE { KEY = 0, OUT = 1, };
void Lock_Unlock_Change_Func(void) { printf("Lock to unlock state.
"); }
void UnLock_lock_Change_Func(void) { printf("UnLock to lock state.
"); }
struct STATE_EVENT { int curstate; int eventcode; int nextstate; void (*changefunc)(void); };
struct STATE_EVENT state_table[] = { {LOCK_STATE, KEY, UNLOCK_STATE, Lock_Unlock_Change_Func}, {UNLOCK_STATE, OUT, LOCK_STATE, UnLock_lock_Change_Func}, };
static int currentstate = LOCK_STATE;
void State_Engine(int event) { int i;
for (i = 0; i < 2; i++) { if (currentstate == state_table.curstate && event == state_table.eventcode) { currentstate = state_table.nextstate; state_table.changefunc(); return; } } printf("Aother thing happend
"); }
int main(int argc, char* argv[]) {
State_Engine(KEY); State_Engine(OUT); State_Engine(OUT); return 0; }
|