备忘录模式

备忘录模式

 

 

[实验任务一]:多次撤销

改进课堂上的用户信息操作撤销实例,使得系统可以实现多次撤销(可以使用HashMapArrayList等集合数据结构实现)。

 

1. 类图:

 

 

 

2. 源代码

#include <iostream>

#include <list>

#include <string>

using namespace std;

 

// 备忘录类

class Memento {

private:

    string accountInfo;

    string passwordInfo;

public:

    Memento(string account, string password) : accountInfo(account), passwordInfo(password) {}

    string getAccountInfo() const { return accountInfo; }

    string getPasswordInfo() const { return passwordInfo; }

};

 

// 原始数据类

class UserInfoDTO {

private:

    string account;

    string password;

public:

    void setAccount(string account) { this->account = account; }

    void setPassword(string password) { this->password = password; }

    string getAccount() const { return account; }

    string getPassword() const { return password; }

    

    Memento* saveMemento() {

        return new Memento(account, password);

    }

    void restoreMemento(Memento* memento) {

        account = memento->getAccountInfo();

        password = memento->getPasswordInfo();

    }

    void show() {

        cout << "Account: " << account << endl;

        cout << "Password: " << password << endl;

    }

};

 

// 管理者类

class Caretaker {

private:

    list<Memento*> mementoList;

public:

    void setMemento(Memento* memento) {

        mementoList.push_front(memento);

    }

    Memento* getMemento() {

        if (!mementoList.empty()) {

            Memento* memento = mementoList.front();

            mementoList.pop_front();

            return memento;

        }

        return nullptr;

    }

};

 

int main() {

    UserInfoDTO* user = new UserInfoDTO();

    Caretaker* caretaker = new Caretaker();

 

    user->setAccount("张三");

    user->setPassword("12345678");

    cout << "状态一:" << endl;

    user->show();

    caretaker->setMemento(user->saveMemento());

    cout << "-----------------------------" << endl;

 

    user->setAccount("李四");

    user->setPassword("6666666");

    cout << "状态二:" << endl;

    user->show();

    caretaker->setMemento(user->saveMemento());

    cout << "-----------------------------" << endl;

 

    user->setAccount("王五");

    user->setPassword("88888888");

    cout << "状态三:" << endl;

    user->show();

    caretaker->setMemento(user->saveMemento());

    cout << "-----------------------------" << endl;

 

    user->restoreMemento(caretaker->getMemento());

    cout << "回到状态二:" << endl;

    user->show();

    cout << "-----------------------------" << endl;

 

    user->restoreMemento(caretaker->getMemento());

    cout << "回到状态一:" << endl;

    user->show();

    cout << "-----------------------------" << endl;

 

    delete user;

    delete caretaker;

    return 0;

}

 

代码:

 

3. 注意编程规范。

 

 

posted @ 2024-11-20 09:23  艾鑫4646  阅读(2)  评论(0编辑  收藏  举报