当然,命令模式是一种常用的设计模式,其主要思想是将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。下面是一段 C 语言代码,展示了如何实现命令模式:
#include <stdio.h>
#include <stdlib.h>
// 定义一个接收者对象
typedef struct Receiver {
void (*Action)();
} Receiver;
void ReceiverAction() {
printf("Receiver action\n");
}
// 定义一个命令对象
typedef struct Command {
void (*Execute)();
Receiver* receiver;
} Command;
void CommandExecute(Command* self) {
self->receiver->Action();
}
// 定义一个调用者对象
typedef struct Invoker {
Command* command;
} Invoker;
void InvokerInvoke(Invoker* self) {
self->command->Execute();
}
int main() {
Receiver* receiver = (Receiver*)malloc(sizeof(Receiver));
receiver->Action = ReceiverAction;
Command* command = (Command*)malloc(sizeof(Command));
command->Execute = (void(*)(void))CommandExecute;
command->receiver = receiver;
Invoker* invoker = (Invoker*)malloc(sizeof(Invoker));
invoker->command = command;
invoker->Invoke = InvokerInvoke;
invoker->Invoke(invoker);
free(receiver);
free(command);
free(invoker);
return 0;
}