C++ command mode of design mode 14 (including sample code)

The command pattern is a behavioral design pattern that encapsulates requests as objects, allowing you to parameterize other objects with different requests, queues, or log requests. The core of this pattern is to decouple the sender and receiver of the request.

The following is a sample code to implement command mode in C++:

#include <iostream>
#include <vector>
// 定义命令接口
class Command {
    
    
public:
    virtual ~Command() {
    
    }
    virtual void Execute() = 0;
};
// 具体命令类:打印命令
class PrintCommand : public Command {
    
    
public:
    void Execute() override {
    
    
        std::cout << "Hello, world!" << std::endl;
    }
};
// 具体命令类:加法命令
class AddCommand : public Command {
    
    
public:
    AddCommand(int a, int b) : a_(a), b_(b) {
    
    }
    void Execute() override {
    
    
        std::cout << a_ << " + " << b_ << " = " << a_ + b_ << std::endl;
    }
private:
    int a_;
    int b_;
};
// 命令调用者
class Invoker {
    
    
public:
    void SetCommand(Command* cmd) {
    
    
        cmd_ = cmd;
    }
    void ExecuteCommand() {
    
    
        if (cmd_) {
    
    
            cmd_->Execute();
        }
    }
private:
    Command* cmd_;
};
int main() {
    
    
    // 创建命令
    Command* print_cmd = new PrintCommand();
    Command* add_cmd = new AddCommand(1, 2);
    // 创建命令调用者
    Invoker invoker;
    // 设置命令并执行
    invoker.SetCommand(print_cmd);
    invoker.ExecuteCommand();
    invoker.SetCommand(add_cmd);
    invoker.ExecuteCommand();
    // 释放内存
    delete print_cmd;
    delete add_cmd;
    return 0;
}

In the above code, we defined a Command interface, which contains an Execute () pure virtual function. PrintCommand and AddCommand are specific command classes, and they respectively implement the Execute() function to complete specific command operations.

The Invoker class is the command invoker, it has a SetCommand() function to set the command, and an ExecuteCommand() function to execute the command.

In the main() function, we first create two concrete command objects, and then create a command caller object. Next, we set the two command objects to the command caller and execute the command. Finally, we free the memory of the command object.

The advantage of the command pattern is that it decouples the request sender from the receiver, allowing for more flexible design of the system. In addition, command objects can be easily combined into compound commands to achieve more complex functions.

Guess you like

Origin blog.csdn.net/dica54dica/article/details/130021285