命令模式(大话设计模式)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;
}
相关推荐
库玛西5 小时前
现代 C++ 智能指针全景指南:从 RAII 思想到工业级实践
c语言·开发语言·c++·笔记·面试
AC赳赳老秦5 小时前
风控岗应用:OpenClaw 采集公开司法与经营异常数据,自动生成企业风险评估报告
大数据·c语言·数据库·人工智能·python·php·openclaw
艺艺生辉6 小时前
从if-else到策略模式
后端·设计模式
小林ixn6 小时前
单例模式:从弹窗管理到全局状态,一个模式搞定
前端·javascript·设计模式
程序员与背包客_CoderZ6 小时前
Linux D-Bus通信协议详解:从入门到C/C++编码实战
linux·服务器·c语言·c++·嵌入式硬件·嵌入式软件·dbus
嵌入式阿蔡7 小时前
HAL库 vs LL库 vs 寄存器:到底用哪个?
c语言·stm32·单片机·嵌入式硬件·嵌入式实时数据库
Yyyyyy~7 小时前
【C】C语言常见概念
c语言
AI人工智能+电脑小能手8 小时前
大白话说Java设计模式-17-装饰器模式(源码剖析篇)
java·spring·设计模式·装饰器模式·源码分析·io流
嵌入式阿蔡9 小时前
CAN总线入门:从协议帧到STM32实战
c语言·stm32·单片机·嵌入式硬件·嵌入式实时数据库
workflower9 小时前
案例 :某交通厅基于AI技术的智能安全运营实践
网络·人工智能·安全·设计模式·机器人