设计模式-行为-Memento(备忘录)模式
又叫快照模式
捕获一个对象的内部状态,以可以还原这个对象的状态。
场景1:需要undo操作的时候,可以在操作之前备份,失败后恢复操作之前的状态

例1
#include "PublicHeaders.h"
#pragma once
#include <string>
class Memento
{
public:
Memento(const std::string & state)
{
this->state = state;
}
void setState(const std::string& state)
{
this->state = state;
}
const std::string getState()const
{
return state;
}
private:
std::string state;
};
class Originator
{
public:
Memento* CreateMemento()
{
if (backup)
{
delete backup;
}
backup = new Memento(state);
return backup;
}
void RestoreMemento()
{
this->state = backup->getState();
}
void RestoreMemento(Memento*mem)
{
this->state = mem->getState();
}
const std::string &getState()const
{
return state;
}
void setState(const std::string& state)
{
this->state = state;
}
void PrintState()
{
std::cout << state << std::endl;
}
private:
Memento *backup = nullptr;
std::string state = "";
};
void testMemento()
{
Originator * ori = new Originator;
ori->setState("old");
ori->PrintState();
ori->CreateMemento();
ori->setState("new");
ori->PrintState();
ori->RestoreMemento();
ori->PrintState();
}
例2
SGZ游戏项目中,网络连接失败后恢复操作前的状态
-- [Comment] -- callErrorCallback copy recovery -- 这3个函数是撤销更改 local function callErrorCallback() t:recovery() end local _copy = 0 function t:copy() _copy = clone(t) end function t:recovery() if _copy ~= 0 then t = _copy end end -- 本地数据转换为json ,便于上传服务器 function t:toJson() end -- [Comment] -- 从json设置 数据 便于服务器下载后,处理 function t:setJson(m_json) if arg == "" then return end end -- [Comment] -- 玩家执行了敏感操作,才会执行,客户端本地缓存 -- @private t.need_upload = false -- 需要上传数据到服务器 t.need_download = true -- 需要下载数据到客户端 。。。。。。。。。。。。