아래 예에서는 구현을 단순화하기 위해서 상태는 ON/OFF두가지 상태만을 가정하였고, 'n' 입력시 ON상태로, 'f' 입력시 OFF상태로 상태 천이를 하도록 하였다.
#include <stdio.h>
/**********************************************************************
*
* 1. Type defination for Power State management
*
**********************************************************************/
typedef enum {ON,OFF} PowerState;
typedef struct
{
PowerState currPS;
void (*on_received_fptr)(struct PwrState **ps );
void (*off_received_fptr)(struct PwrState **ps );
}PwrState;
/**********************************************************************
*
* 2. Function table for each State.
*
**********************************************************************/
//Prefix ON/OFF means current status when these functions are called.
void ON_off_received(PwrState **ps );
void OFF_on_received(PwrState **ps );
void null_func(PwrState **ps);//C에서는 가상 함수를 사용할 수 없기 때문에, 아래와 같은 각 상태별
//함수 테이블을 별도로 유지해야 한다.
PwrState psON= {ON, null_func, ON_off_received};
PwrState psOFF={OFF, OFF_on_received, null_func};
void ON_off_received(PwrState **ps)
{
printf("Currnt State =%d : 0:ON 1:OFF \n",(int)(*ps)->currPS);
printf("%s is called\n",__func__);
printf("change curr power state from ON to OFF\n");
*ps=&psOFF;
}
void OFF_on_received(PwrState **ps)
{
printf("Currnt State =%d : 0:ON 1:OFF \n",(int)(*ps)->currPS);
printf("%s is called\n",__func__);
printf("change curr power state from OFF to ON\n");
*ps=&psON;
}
void null_func(PwrState **ps){}
int main(void)
{
char keyin;
PwrState *ps=&psOFF;
printf("Current power state is OFF\n");
printf("type \'n\' to change power state to ON\n");
printf("type \'f\' to change power state to OFF\n");
while(1)
{
keyin = getchar();
switch(keyin)
{
case 'n':// change state to ON
ps->on_received_fptr(&ps);
break;
case 'f':// change state to OFF
ps->off_received_fptr(&ps);
break;
default:
break;
}
}
}