1 含义
在不暴露对象实现细节的情况下保存和恢复对象之前的状态。
2 模式结构
3 代码实现
举例:用户信息操作撤销
#include <iostream>
#include <string>
using namespace std;
//备忘录Memento
class Memento
{
private:
string account;
string password;
string telNo;
public:
Memento(string account,string password,string telNo)
{
this->account = account;
this->password = password;
this->telNo = telNo;
}
string getAccount() {
return account;
}
void setAccount(string account) {
this->account = account;
}
string getPassword() {
return password;
}
void setPassword(string password) {
this->password = password;
}
string getTelNo() {
return telNo;
}
void setTelNo(string telNo) {
this->telNo = telNo;
}
};
//原发器UserInfoDTO(用户信息类)
class UserInfoDTO
{
private:
string account;
string password;
string telNo;
public:
string getAccount() {
return account;
}
void setAccount(string account) {
this->account = account;
}
string getPassword() {
return password;
}
void setPassword(string password) {
this->password = password;
}
string getTelNo() {
return telNo;
}
void setTelNo(string telNo) {
this->telNo = telNo;
}
Memento* saveMemento()
{
return new Memento(account, password, telNo);
}
void restoreMemento(Memento* memento)
{
this->account = memento->getAccount();
this->password = memento->getPassword();
this->telNo = memento->getTelNo();
}
void show()
{
cout << "Account:" << this->account << endl << "Password:" << this->password << endl
<< "TelNo:" << this->telNo << endl;
}
};
//负责人Caretaker
class Caretaker {
public:
Caretaker() {}
Memento* getMemento() {
return memento.get();}
void setMemento(Memento *memento) {
this->memento.reset(memento);}
private:
shared_ptr<Memento> memento;
};
int main(int argc, char* argv[])
{
//创建原发器和负责人
UserInfoDTO user;
Caretaker c;
//定义初始状态
user.setAccount("zhasan");
user.setPassword("123");
user.setTelNo("1300");
cout << "状态一:" << endl;
user.show();
//保存状态
c.setMemento(user.saveMemento());
cout << "----------" << endl;
//更改状态
user.setPassword("111");
user.setTelNo("1311");
cout << "状态二:" << endl;
user.show();
cout << "----------" << endl;
//恢复状态
user.restoreMemento(c.getMemento());
cout << "回到状态一:" << endl;
user.show();
return 0;
}
4 优缺点
优点:
不破坏对象封装情况的前提下创建对象状态快照。
缺点:
负责人必须完整跟踪原发器的生命周期, 这样才能销毁弃用的备忘录。
绝大部分动态编程语言 (例如 PHP、 Python 和 JavaScript) 不能确保备忘录中的状态不被修改。
5 适用场景
当你需要创建对象状态快照来恢复其之前的状态时, 可以使用备忘录模式。
当直接访问对象的成员变量、 获取器或设置器将导致封装被突破时, 可以使用该模式。
6.与其他模式的关系
你可以同时使用命令模式和备忘录模式来实现 “撤销”。 在这种情况下, 命令用于对目标对象执行各种不同的操作, 备忘录用来保存一条命令执行前该对象的状态。
你可以同时使用备忘录和迭代器模式来获取当前迭代器的状态, 并且在需要的时候进行回滚。
有时候原型模式可以作为备忘录的一个简化版本, 其条件是你需要在历史记录中存储的对象的状态比较简单, 不需要链接其他外部资源, 或者链接可以方便地重建。
参考
1.https://blog.csdn.net/lxq1997/article/details/91549031
2.https://refactoringguru.cn/design-patterns/memento