命令模式
C++
#include <iostream>
using namespace std;
class Receiver
{
public:
void action()
{
cout << "请求执行!" << endl;
}
};
class Command
{
protected:
Receiver *receiver;
public:
Command(Receiver *receiver) : receiver(receiver) {}
virtual ~Command(){};
virtual void Execute() = 0;
};
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver *receiver) : Command(receiver)
{
}
virtual void Execute()
{
receiver->action();
}
};
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
#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 = {.action = receiver_action};
Command concrete_command_base = {.execute = concrete_command_execute, .receiver = &receiver};
ConcreteCommand concrete_command = {.base = concrete_command_base};
Invoker invoker = {.command = (Command *)&concrete_command};
invoker.command->execute(invoker.command);
return 0;
}