91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

c++命令模式如何實現撤銷功能

c++
小樊
81
2024-11-23 19:51:34
欄目: 編程語言

在C++中,實現命令模式的撤銷功能需要遵循以下步驟:

  1. 定義一個命令接口(Command):
class Command {
public:
    virtual ~Command() {}
    virtual void execute() = 0;
    virtual void undo() = 0;
};
  1. 為每個具體命令創建一個類,實現命令接口:
class ConcreteCommandA : public Command {
private:
    Receiver* receiver;

public:
    ConcreteCommandA(Receiver* receiver) : receiver(receiver) {}

    void execute() override {
        receiver->actionA();
    }

    void undo() override {
        receiver->undoActionA();
    }
};

class ConcreteCommandB : public Command {
private:
    Receiver* receiver;

public:
    ConcreteCommandB(Receiver* receiver) : receiver(receiver) {}

    void execute() override {
        receiver->actionB();
    }

    void undo() override {
        receiver->undoActionB();
    }
};
  1. 創建一個命令管理器(CommandManager),用于存儲和管理命令對象,并提供執行和撤銷功能:
#include <stack>

class CommandManager {
private:
    std::stack<Command*> commandStack;

public:
    void executeCommand(Command* command) {
        command->execute();
        commandStack.push(command);
    }

    void undoLastCommand() {
        if (!commandStack.empty()) {
            Command* command = commandStack.top();
            commandStack.pop();
            command->undo();
        }
    }
};
  1. 創建一個接收者(Receiver)類,包含實際要執行的操作和撤銷操作:
class Receiver {
public:
    void actionA() {
        // 實際執行操作A
    }

    void undoActionA() {
        // 撤銷操作A
    }

    void actionB() {
        // 實際執行操作B
    }

    void undoActionB() {
        // 撤銷操作B
    }
};
  1. 在客戶端代碼中,使用命令模式執行和撤銷操作:
int main() {
    Receiver receiver;
    CommandManager commandManager;

    Command* commandA = new ConcreteCommandA(&receiver);
    Command* commandB = new ConcreteCommandB(&receiver);

    commandManager.executeCommand(commandA);
    commandManager.executeCommand(commandB);

    commandManager.undoLastCommand();

    delete commandA;
    delete commandB;

    return 0;
}

這樣,我們就實現了一個簡單的命令模式的撤銷功能。當然,實際應用中可能需要根據具體需求對這個實現進行擴展和優化。

0
理塘县| 灵石县| 定州市| 马关县| 上犹县| 锡林浩特市| 靖边县| 云浮市| 太仆寺旗| 台东市| 蕲春县| 大安市| 望奎县| 加查县| 扬州市| 南丹县| 肇州县| 西峡县| 安宁市| 承德县| 德惠市| 金门县| 都江堰市| 融水| 土默特右旗| 沾化县| 阳东县| 汉川市| 凤阳县| 鄂托克前旗| 虎林市| 象山县| 峨边| 宁南县| 武平县| 潞城市| 赤峰市| 册亨县| 望江县| 昌黎县| 广东省|