状态模式是设计模式中的一种。它允许对象在其内部状态改变时改变它的行为。下面是一个c语言实现状态模式的例子:
#include <stdio.h>
// 抽象状态类
typedef struct State State;
struct State {
void (*handle)(State*);
};
// 具体状态类
typedef struct ConcreteStateA ConcreteStateA;
struct ConcreteStateA {
State state;
};
void handleA(State* state) {
printf("处理A\n");
}
typedef struct ConcreteStateB ConcreteStateB;
struct ConcreteStateB {
State state;
};
void handleB(State* state) {
printf("处理B\n");
}
// 环境类
typedef struct Context Context;
struct Context {
State* state;
};
void request(Context* context) {
context->state->handle(context->state);
}
int main() {
ConcreteStateA stateA;
stateA.state.handle = handleA;
ConcreteStateB stateB;
stateB.state.handle = handleB;
Context context;
context.state = (State*) &stateA;
request(&context);
context.state = (State*) &stateB;
request(&context);
return 0;
}