命令模式——C++实现
问题描述:
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
类图:
代码:
#include<iostream> #include<vector> #include<stack> using namespace std; //接受者 class Adder { private: int num; public: Adder(){ this->num=0; } int add(int value) { num += value; return num; } }; //抽象命令 class Command { public: virtual int execute(int value) = 0; virtual int undo() = 0; virtual int redo() = 0; }; //具体命令 class AddCommand : public Command { private: Adder adder; stack <int>unStack; stack <int>reStack; public: int undo() { int i = 0; if (unStack.empty()) { i = -1; } else { reStack.push(unStack.top()); unStack.pop(); if (!unStack.empty()) { i = unStack.top(); } } return i; } int redo() { int i = 0; if (reStack.empty()) { i = -1; } else {//撤回时只要可以可以撤回,则撤回栈一定有数据 unStack.push(reStack.top()); i = reStack.top(); reStack.pop(); } return i; } int execute(int value) { int v = 0; v = adder.add(value); cout << v << endl; unStack.push(v); return v; } }; //调用者 class Invoker{ private: AddCommand command; public: void setCommand(AddCommand command2) { command = command2; }; void compute(int value) { command.execute(value); }; void undo() { int i = command.undo(); if (i == -1) { cout << "已撤销到初态" << endl; } else { cout << "执行成功,运算结果是:" << i << endl; } } void redo() { int i = command.redo(); if (i == -1) { cout << "已恢复至终态" << endl; } else { cout << "执行成功,运算结果是:" << i << endl; } } }; //测试函数 int main() { Invoker inv; AddCommand command; inv.setCommand(command); //计算 cout << "计算过程:" << endl; inv.compute(1); inv.compute(2); inv.compute(3); //多次撤回 cout << "undo操作:" << endl; inv.undo(); inv.undo(); inv.undo(); inv.undo(); //多次恢复 cout << "redo操作:" << endl; inv.redo(); inv.redo(); inv.redo(); inv.redo(); }
运行截图: