首页 > 编程语言 > 详细

C语言与设计模式 之 三

时间:2019-12-09 12:07:04      阅读:75      评论:0      收藏:0      [点我收藏+]

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函数指针会响应该状态下的事件。
对象 —— 对象的操作接口。
优点:利于扩展 —— 添加新的状态对象 和 它的操作接口。

C语言与设计模式 之 三

原文:https://www.cnblogs.com/vonyoven/p/12009775.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!