當狀態位有三種以上,我們用面向對象的狀態設置;
下面是現代編程 ,CD 播放機的狀態設置;
State.h
#ifndef _STATE_H #define _STATE_H #include <stddef.h> #include <stdio.h> #ifdef _cplusplus extren "C" { #endif typedef struct State { const struct State *(* const stop)(const struct State *pThis); const struct State *(* const playOrPause)(const struct State *pThis); }State; static const State *pCurrentState; void initialize(); void onStop(); void onPlayOrPause(); const State *ignore(const State *pThis); const State *startPlay(const State *pThis); const State *stopPlay(const State *pThis); const State *pausePlay(const State *pThis); const State *resumePlay(const State *pThis); static const State IDlE = { ignore, startPlay}; static const State PLAY = {stopPlay , pausePlay}; static const State PAUSE = {stopPlay , resumePlay}; #ifdef _cplusplus } #endif #endif
State.cpp
#include "State.h" #include <stdio.h> static unsigned int count = 0; void initialize() { pCurrentState = &IDlE; } void onStop() { pCurrentState = pCurrentState->stop(pCurrentState); } void onPlayOrPause() { pCurrentState = pCurrentState->playOrPause(pCurrentState); } static const State *ignore(const State *pThis) { printf("[%d] %s\n",++count,"ignore"); return pCurrentState; } static const State *startPlay(const State *pThis) { printf("[%d] %s\n", ++count, "startPlay"); return &PLAY; } static const State *stopPlay(const State *pThis) { printf("[%d] %s\n", ++count, "stopPlay"); return &IDlE; } static const State *pausePlay(const State *pThis) { printf("[%d] %s\n", ++count, "pausePlay"); return &PAUSE; } static const State *resumePlay(const State *pThis) { printf("[%d] %s\n", ++count, "resumePlay"); return &PLAY; }
main.cpp
#include "State.h" #include <stdio.h> int main() { initialize(); printf("--------------\n"); onPlayOrPause();//開始 printf("--------------\n"); onPlayOrPause();//暫停 printf("--------------\n"); onPlayOrPause();//繼續 printf("--------------\n"); onPlayOrPause();//暫停 printf("--------------\n"); onPlayOrPause();//繼續 printf("--------------\n"); onStop(); return 0; }
運行結果
它的狀態圖
《C現代編程》第四章 C語言與設計模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.