C++ implementation of the command mode (Command) of the design mode

1. Proposal of command mode

In the process of software development, "behavior requester" and "behavior implementer" usually present a kind of "tight coupling". If the implementation of behavior changes frequently, it is not conducive to code maintenance. The command pattern can decouple the requester of the behavior from the implementer of the behavior. The specific process is to encapsulate the behavior requester into an object, and abstract the behavior implementer into a class.

2. Requirements description

There are two different behaviors, and the two different behaviors correspond to different operations. Design a code that can implement different behaviors corresponding to different processing behaviors.

3. Function realization

(1) The UML diagram is as follows:

 

 (2) The code implementation is as follows:

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

The result of the program running is as follows:

Guess you like

Origin blog.csdn.net/hanxiaoyong_/article/details/132525642