设计模式 C++命令模式 模拟撤销恢复

#include <iostream>
#include <list>
#include<algorithm>
#include<sstream>
#include<stack>
#include <queue>
using namespace std;
class Adder
{
private:
    int num = 0;
public:
    int add(int value)
    {
        num += value;
        return num;
    }
};
class AbstractCommand
{
public:
    virtual int execute(int value) = 0;
    virtual int undo() = 0;
    virtual int redo() = 0;
};
class CalculatorForm
{
private:
    AbstractCommand* command;
public:
    void setCommand(AbstractCommand* command) 
    {
        this->command = command;
    }
    void compute(int value) 
    {
        int i = (*command).execute(value);
        string i_str;
        stringstream sStream;
        sStream << i;
        sStream >> i_str;
        cout << "执行运算,运算结果为:" + i_str << endl;
    }
    void undo() 
    {
        int i = (*command).undo();
        string i_str;
        stringstream sStream;
        sStream << i;
        sStream >> i_str;
        cout << "执行撤销,运算结果为:" + i_str << endl;
    }
    void redo()
    {
        int i = (*command).redo();
        string i_str;
        stringstream sStream;
        sStream << i;
        sStream >> i_str;
        cout << "执行恢复,运算结果为:" + i_str << endl;
    }
};
class ConcreteCommand :public  AbstractCommand
{
private:
    Adder adder;
    int value;
    stack<int> st;
    queue<int> q;
public:
    int execute(int value) 
    {
        this->value = value;
        st.push(value);
        return adder.add(value);
    }
    int undo() 
    {
        value = st.top();
        q.push(value);
        st.pop();
        return adder.add(-value);
    }
    int redo()
    {
        value = q.front();
        q.pop();
        return adder.add(value);
    }
};
int main()
{
    CalculatorForm form;
    AbstractCommand* command;
    command = new ConcreteCommand();
    form.setCommand(command);
    form.compute(10);
    form.compute(5);
    form.compute(10);
    cout<<"第一次撤销:"<<endl;
    form.undo();
    cout << "第二次撤销:" << endl;
    form.undo();
    cout << "第三次撤销:" << endl;
    form.undo();
    cout << "第一次恢复:" << endl;
    form.redo();
    cout << "第二次恢复:" << endl;
    form.redo();
    cout << "第三次恢复:" << endl;
    form.redo();

}

 

posted @ 2021-11-16 09:32  风吹过半夏  阅读(263)  评论(0编辑  收藏  举报