命令模式(大话设计模式)C/C++版本

命令模式

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;
}
相关推荐
极客代码4 小时前
Unix 域套接字(本地套接字)
linux·c语言·开发语言·unix·socket·unix域套接字·本地套接字
达帮主5 小时前
16. C语言二级指针
c语言·开发语言·汇编·青少年编程
代码不停5 小时前
C语言——结构体、联合、枚举
c语言·开发语言·windows
"_rainbow_"5 小时前
Qt按钮控件常用的API
qt·命令模式
_GR5 小时前
2020年蓝桥杯第十一届C&C++大学B组(第二次)真题及代码
c语言·数据结构·c++·算法·蓝桥杯
C语言小火车6 小时前
Redis 10大核心场景实战手册:从缓存加速到分布式锁的全面解析
c语言·开发语言·数据库·c++·redis
小成喝橙汁补维C6 小时前
C语言:基于链表实现栈
c语言·数据结构·算法
xiecoding.cn7 小时前
C语言和C++到底有什么关系?
c语言·开发语言·c++·c/c++·c语言入门
Run_Teenage7 小时前
C语言每日一练——day_11
c语言·开发语言
带鱼吃猫8 小时前
C语言文件操作入门
c语言·开发语言