C语言与设计模式 之 三

cdplayer.h

#ifndef _CDPLAYER_H_
#define _CDPLAYER_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct State {
    const struct State *(* const stop)(const struct State *pThis);
    const struct State *(* const playorpause)(const struct State *pThis);
}State;
void initialize();
void onStop();
void onPlayOrPause();
#ifdef __cplusplus
}
#endif
#endif
 
cdplayer.c
#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函数指针会响应该状态下的事件。
对象 —— 对象的操作接口。
优点:利于扩展 —— 添加新的状态对象 和 它的操作接口。
posted @ 2019-12-09 10:56    阅读(183)  评论(0)    收藏  举报