#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct{
int index;
}Owner;
typedef enum{
START,PLAY,STOP
}State;
State startState(Owner *owner){
owner->index++;
printf("..");
if(owner->index%5==0){
printf(">>");
return PLAY;
}
return START;
}
State playState(Owner *owner){
owner->index++;
switch(owner->index%5){
case 0: case 3: case 2:printf("~!~");break;
case 1: printf("~@~");break;
case 4: printf(">>");return STOP;
}
return PLAY;
}
State stopState(Owner *owner){
owner->index++;
printf("**");
if(owner->index%5==1){
printf(">>");
return START;
}
return STOP;
}
typedef State (*HandleState)(Owner *);
HandleState handleState[]={startState,playState,stopState};
int main(){
Owner owner={0};
State currentState=STOP;
for(int i=0;i<100;i++){
currentState=handleState[currentState](&owner);
}
return 0;
}
typedef struct {
void (*handle)(void);
} State;
void handleStateA() { printf("State A\n"); }
void handleStateB() { printf("State B\n"); }
State stateA = { .handle = handleStateA };
State stateB = { .handle = handleStateB };
typedef struct {
State* currentState;
} Context;
// 使用
Context ctx = { .currentState = &stateA };
ctx.currentState->handle(); // 输出 "State A"