天天看點

每日總結

軟體設計模式   備忘錄模式:

改進課堂上的“使用者資訊操作撤銷”執行個體,使得系統可以實作多次撤銷(可以使用HashMap、ArrayList等集合資料結構實作)。

每日總結

#include <iostream>

#include <string>

#include <vector>

using namespace std;

class AbstractCommand {

public:

    virtual int execute(int value) = 0;

    virtual int undo() = 0;

};

class Adder {

    int num = 0;

    int add(int value) { num += value; return num; };

class ConcreteCommand :public AbstractCommand {

    Adder* adder = new Adder();

    vector<int>* list;

    ConcreteCommand() { this->list = new vector<int>; };

    int execute(int value) {

        list->push_back(value);

        return adder->add(value);

    };

    int undo() {

        if (list->size() > 0) {

            int value = list->at(list->size() - 1);

            list->pop_back();

            return adder->add(-value);

        }

        else {

            return 0;

class CalculatorForm {

    AbstractCommand* command;

    void setCommand(AbstractCommand* command) {

        this->command = command;

    void compute(int value) {

        int i = command->execute(value);

        cout << "執行運算,運算結果為:" << i << endl;

    }

    void undo() {

        int i = command->undo();

        cout << "執行撤銷,運算結果為:" << i << endl;

int main() {

    CalculatorForm* form = new CalculatorForm();

    ConcreteCommand* command = new ConcreteCommand();

    form->setCommand(command);

    bool flag = true;

    while (flag) {

        cout << "請輸入想要操作的選項,1為計算,-1為撤銷,0為退出" << endl;

        int n;

        cin >> n;

        switch (n) {

        case 1:

            cout << "請輸入想要添加的數值" << endl;

            int m;

            cin >> m;

            form->compute(m);

            break;

        case -1:

            form->undo();

        case 0:

            flag = false;

        default:

            cout << "輸入錯誤請重新輸入!!\n";

}