命令模式
C++
cpp
#include <iostream>
using namespace std;
// Receiver类 知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接收者
class Receiver
{
public:
void action()
{
cout << "请求执行!" << endl;
}
};
// Command类,用来声明执行操作的接口
class Command
{
protected:
Receiver *receiver;
public:
Command(Receiver *receiver) : receiver(receiver) {}
virtual ~Command(){};
virtual void Execute() = 0; // 抽象执行命令接口
};
// ConcreteCommand类 将一个接收者对象绑定于一个动作 调用接收者相应的操作 以实现Execute
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver *receiver) : Command(receiver)
{
}
virtual void Execute()
{
receiver->action();
}
};
// Invoker类,要求该命令执行这个请求
class Invoker
{
private:
Command *command;
public:
void SetCommand(Command *command)
{
this->command = command;
}
void ExecuteCommand()
{
return command->Execute();
}
};
int main()
{
Receiver *r = new Receiver();
Command *c = new ConcreteCommand(r);
Invoker *i = new Invoker();
i->SetCommand(c);
i->ExecuteCommand();
delete i;
i = nullptr;
delete c;
c = nullptr;
delete r;
r = nullptr;
return 0;
}
C
c
#include <stdio.h>
typedef struct Receiver
{
void (*action)(struct Receiver *self); // 行动函数
} Receiver;
typedef struct Command
{
void (*execute)(struct Command *self); // 执行函数
Receiver *receiver; // 接收者
} Command;
typedef struct Invoker
{
Command *command; // 命令
} Invoker;
void receiver_action(Receiver *self)
{
printf("请求执行!\n");
}
typedef struct ConcreteCommand
{
Command base; // 基础命令
} ConcreteCommand;
void concrete_command_execute(Command *self)
{
self->receiver->action(self->receiver);
}
int main()
{
// 初始化 Receiver
Receiver receiver = {.action = receiver_action};
// 初始化 ConcreteCommand
Command concrete_command_base = {.execute = concrete_command_execute, .receiver = &receiver};
ConcreteCommand concrete_command = {.base = concrete_command_base};
// 初始化 Invoker
Invoker invoker = {.command = (Command *)&concrete_command};
// 执行命令
invoker.command->execute(invoker.command);
return 0;
}