zoukankan      html  css  js  c++  java
  • 设计模式 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();
    
    }
  • 相关阅读:
    费用流
    平面最近点对
    纸牌均分问题
    cdq分治模板
    费解的开关
    斐波那契和排列组合性质
    主席树
    Springboot使用EasyExcel(仅限自己收藏)
    vue项目中h5移动端中通过flex布局实现首尾固定,中间滚动(借鉴)
    vue路由参数的获取、添加和替换
  • 原文地址:https://www.cnblogs.com/fengchuiguobanxia/p/15559620.html
Copyright © 2011-2022 走看看