设计模式之命令模式(Command)的C++实现

1、命令模式的提出

在软件开发过程中,"行为请求者"和"行为实现者"通常呈现一种"紧耦合",如果行为的实现经常变化,则不利于代码的维护。命令模式可以将行为的请求者和行为的实现者进行解耦。具体流程是将行为请求者封装成一个对象,将行为实现者抽象成一个类。

2、需求描述

有2两种不同的行为,两种不同行为分别对应不同的操作。设计一个代码,可以实现不同的行为对应不同的处理行为。

3、功能实现

(1)UML图如下:

(2)代码实现如下:

cpp 复制代码
#include <iostream>
#include <vector>

// 命令接口
class Command {
public:
    Command(std::string cmd):m_strCmd(cmd){};
    virtual ~Command() {}
    virtual void execute() = 0;
    std::string& getCmd(){return m_strCmd;};
private:
    std::string m_strCmd;
};


class ConcreteCommand1 : public Command {
public:
    ConcreteCommand1(std::string str):Command(str){};
    void execute() override {
        std::cout << "ConcreteCommand1: " << getCmd() << std::endl;
        // todo something...
    }
};

class ConcreteCommand2 : public Command {
public:
    ConcreteCommand2(std::string str):Command(str){};
    void execute() override {
        std::cout << "ConcreteCommand2: " << getCmd() << std::endl;
        // todo something...
    }
};

// 命令请求者
class Requester {
private:
    std::vector<Command*> m_vecCommands;

public:
    void aadCommand(Command* cmd) {
        m_vecCommands.emplace_back(cmd);
    }

    void executeCommand() {
        for(auto& it:m_vecCommands)
        {
            it->execute();
        }
    }
};

class Client
{
public:
	void doWork()
	{
	    Requester request;
        Command* command1 = new ConcreteCommand1("Command1");
        Command* command2 = new ConcreteCommand2("Command2");
	    
        request.aadCommand(command1);
        request.aadCommand(command2);
        request.executeCommand();
	   
        delete command1;
        delete command2;
        command1 = nullptr;
        command2 = nullptr;
	};
}

int main() {
	Client obj;
	obj.doWork();
    return 0;
}

程序运行结果如下:

相关推荐
玖玥拾1 天前
C/C++ 基础笔记(十一)类的进阶
c语言·c++·设计模式·
Jun6261 天前
QT(2)-通过管道关联CMD
开发语言·qt·命令模式
geovindu2 天前
go: Broadcast Pattern
开发语言·后端·设计模式·golang·广播模式
我爱cope2 天前
【Agent智能体23 | 规划-规划工作流】
人工智能·设计模式·语言模型·职场和发展
lengjingzju2 天前
符·形·音·意(SFEM):一种面向通用智能的四维认知架构
设计模式·ai·学习方法
Drone_xjw2 天前
Qt国际化多语言配置详解-入门到精通
开发语言·qt·命令模式
贵慜_Derek2 天前
《从零实现 Agent 系统》连载 23|Skill 体系与 Skill Creator:能力打包与迭代
人工智能·设计模式·架构
张小姐的猫2 天前
【Linux】多线程 —— 线程池 | 单例模式 | 常见锁
linux·运维·服务器·c++·单例模式·设计模式·策略模式
老码观察2 天前
设计模式实战解读(十二):状态模式——干掉状态机里的 if-else 地狱
设计模式·状态模式
我爱cope2 天前
【Agent智能体24 | 规划-创建和执行LLM计划】
人工智能·设计模式·语言模型·职场和发展