一个CD播放器的例子:
cdplayer.h
#ifndef _CDPLAYER_H_
#define _CDPLAYER_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
EV_STOP,
EV_PLAY_PAUSE
}EventCode;
void initialize();
void OnEvent(EventCode ec);
static void startPlayer();
static void pausePlayer();
static void resumePlayer();
static void stopPlayer();
#ifdef __cplusplus
}
#endif
#endif
cdplayer.c
#include <stdbool.h>
#include <stdio.h>
#include "cdplayer.h"
bool playflg;
bool pauseflag;
void initialize() {
playflg = false;
pauseflag = false;
}
void OnEvent(EventCode ec){
switch(ec){
case EV_STOP:
if(playflg == true || pauseflag == true)
stopPlayer();
break;
case EV_PLAY_PAUSE:
if(playflg == true)
pausePlayer();
else if(pauseflag == true)
resumePlayer();
else
startPlayer();
break;
default:
break;
}
}
static void startPlayer(){
playflg = true;
pauseflag = false;
//do something to start player
printf("start\n");
}
static void pausePlayer(){
playflg = false;
pauseflag = true;
//do something to pause player
printf("pause\n");
}
static void resumePlayer(){
playflg = true;
pauseflag = false;
//do something to resume player
printf("resume\n");
}
static void stopPlayer(){
playflg = false;
pauseflag = false;
//do something to stop player
printf("stop\n");
}
cdplayer_test.c
#include "cdplayer.h" int main(int argc, char const *argv[]{initialize();
OnEvent(EV_PLAY_PAUSE);
OnEvent(EV_PLAY_PAUSE);
OnEvent(EV_PLAY_PAUSE);
OnEvent(EV_STOP);
return 0;
}
代码好写,不好阅读(两个状态变量来表现三种状态),不好扩展。