可以用c语言展示一下23设计模式中的命令模式吗
时间: 2023-02-28 07:20:30 浏览: 74
当然可以!命令模式是23种设计模式中的一种,它通过将请求封装成对象,从而让请求发送者与请求接收者解耦,进而达到解除请求与实现之间的耦合。下面是一份c语言代码的简单示例:
```
#include <stdio.h>
// 抽象命令类
typedef struct Command Command;
struct Command {
void (*execute)(Command *self);
};
// 具体命令类
typedef struct ConcreteCommand ConcreteCommand;
struct ConcreteCommand {
Command command;
void (*setReceiver)(ConcreteCommand *self, int value);
int receiver;
};
void concreteCommandExecute(Command *command) {
ConcreteCommand *self = (ConcreteCommand*)command;
printf("Receiver value: %d\n", self->receiver);
}
void concreteCommandSetReceiver(ConcreteCommand *self, int value) {
self->receiver = value;
}
// 客户端代码
int main() {
ConcreteCommand command;
command.command.execute = concreteCommandExecute;
command.setReceiver = concreteCommandSetReceiver;
command.setReceiver(&command, 42);
command.command.execute((Command*)&command);
return 0;
}
```
这份代码实现了命令模式的核心思想:把请求封装成对象。如果有什么疑问,请随时告诉我。