#include <stdio.h>
#include "cdplayer.h"
static const State *pCurrentState = NULL;
static const State *ignore(const State *pThis);
static const State *startplay(const State *pThis);
static const State *stopplay(const State *pThis);
static const State *pauseplay(const State *pThis);
static const State *resumeplay(const State *pThis);
const State IDLE = {
ignore,
startplay
};
const State PLAY = {
stopplay,
pauseplay
};
const State PAUSE = {
stopplay,
resumeplay
};
void initialize(){
pCurrentState = &IDLE;
}
void onStop(){
pCurrentState = pCurrentState->stop(pCurrentState);
}
void onPlayOrPause(){
pCurrentState = pCurrentState->playorpause(pCurrentState);
}
static const State *ignore(const State *pThis){
//do nothing
printf("do nothing\n");
return pCurrentState;
}
static const State *startplay(const State *pThis){
//start play
printf("start play\n");
return &PLAY;
}
static const State *stopplay(const State *pThis){
//stop play
printf("stop play\n");
return &IDLE;
}
static const State *pauseplay(const State *pThis){
//pause play
printf("pause play\n");
return &PAUSE;
}
static const State *resumeplay(const State *pThis){
//resume play
printf("resume play\n");
return &PLAY;
}
cdplayer_test.c
#include "cdplayer.h"
int main(int argc, char const *argv[]){
initialize();
onPlayOrPause();
onPlayOrPause();
onPlayOrPause();
onStop();
return 0;
}
面向对象的状态模式
State是表示状态的对象,它内部的stop和playorpause函数指针会响应该状态下的事件。
对象 —— 对象的操作接口。
优点:利于扩展 —— 添加新的状态对象 和 它的操作接口。