备忘录模式
备忘录模式
[实验任务一]:多次撤销
改进课堂上的“用户信息操作撤销”实例,使得系统可以实现多次撤销(可以使用HashMap、ArrayList等集合数据结构实现)。
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. 注意编程规范。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示