状态机-面向对象编程
#include "stdio.h"
//状态
typedef struct State {
const struct State *(* const state_press)(const struct State *pThis);
const struct State *(* const state_release)(const struct State *pThis);
} State;
//事件--改变状态
void initialize(void);
void press_button(void);
void release_button(void);
//调用函数
static const State *pCurrentState=NULL;
static const State *ignore(const State *pThis);
static const State *press(const State *pThis);
static const State *release(const State *pThis);
//迁移过程
const State IDLE = {
press,
ignore
};
const State PRESS = {
ignore,
release
};
const State RELEASE = {
press,
ignore
};
//事件具体实现--改变状态
void initialize(void)
{
pCurrentState = &IDLE;
}
void press_button()
{
pCurrentState = pCurrentState->state_press(pCurrentState);
}
void release_button()
{
pCurrentState = pCurrentState->state_release(pCurrentState);
}
static const State *ignore(const State *pThis)
{
printf("nothing to do
");
return pCurrentState;
}
static const State *press(const State *pThis)
{
printf("按键1按下
");
return &PRESS;
}
static const State *release(const State *pThis)
{
printf("按键1松开
");
return &RELEASE;
}
int main(void)
{
initialize();
press_button();
press_button();
release_button();
release_button();
return 0;
}