用c语言展示一下23种设计模式中的状态模式
时间: 2023-02-28 15:38:03 浏览: 84
状态模式是设计模式中的一种。它允许对象在其内部状态改变时改变它的行为。下面是一个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;
}
```
输出:
```
处理A
处理B
```
上面的代码实现了状态模式。环境类`Context`具有一个指向状态类的指针,并可以通过该指针来请求处理。在环境类中,状态可以改变,并导致环境类的行为发生变化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)