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

命令模式

在这里插入图片描述

C++

#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

#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;
}

相关推荐

  1. 简单工厂模式(大话设计模式)C/C++版本

    2024-07-12 13:48:05       21 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 13:48:05       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 13:48:05       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 13:48:05       58 阅读
  4. Python语言-面向对象

    2024-07-12 13:48:05       69 阅读

热门阅读

  1. tkinter的iconbitmap默认图标

    2024-07-12 13:48:05       19 阅读
  2. 【SQL】MySQL 的乐观锁和悲观锁

    2024-07-12 13:48:05       21 阅读
  3. 排序列表 原生方法和comparator方法

    2024-07-12 13:48:05       23 阅读
  4. 音频demo:将PCM数据和Speex数据进行相互编解码

    2024-07-12 13:48:05       22 阅读
  5. MySQL(基础篇)

    2024-07-12 13:48:05       21 阅读
  6. ES6 Class(类) 总结(九)

    2024-07-12 13:48:05       20 阅读