设计模式之命令模式(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;
}

程序运行结果如下:

相关推荐
刀法如飞12 小时前
AI时代,程序员都应该是算法思想工程师
人工智能·设计模式·程序员
在西安放羊的牛油果18 小时前
我把 2000 行下单代码,重构成了一套交易前端架构
前端·设计模式·架构
寅时码2 天前
React 正在演变为一场不可逆的赛博瘟疫:AI 投毒、编译器迷信与装死的官方
前端·react.js·设计模式
willow5 天前
Axios由浅入深
设计模式·axios
七月丶7 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞7 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼7 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟7 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder7 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式