当状态位有三种以上,我们用面向对象的状态设置;
下面是现代编程 ,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语言与设计模式
最新推荐文章于 2021-05-18 06:33:22 发布