标签:code 游戏 tst bubuko delete 技术 private info block
备忘录(Memento),在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。[DP]
#include <iostream>
#include <string>
struct State
{
std::string m_switch;
std::string m_other;
};
class Memento
{
public:
Memento(State s) :m_state(s){}
State GetState(){ return m_state; }
private:
State m_state;
};
class Originator
{
public:
Memento* CreateMemento(){
return new Memento(m_state);
}
void Recovery(Memento *m){
m_state = m->GetState();
}
void SetState(const State &s){
m_state = s;
}
void Show(){
std::cout << "state is " << m_state.m_switch << std::endl;
}
private:
State m_state;
};
class Caretaker
{
public:
void SetMemento(Memento *m){
m_memento = m;
}
Memento* GetMemento(){
return m_memento;
}
private:
Memento *m_memento;
};
void Client()
{
Originator* o = new Originator();
o->SetState(State{ "on", "" });
o->Show();
Memento* m = o->CreateMemento();
Caretaker c;
c.SetMemento(m);
o->SetState(State{ "off", "" });
o->Show();
o->Recovery(c.GetMemento());
o->Show();
delete o;
delete m;
}
int main()
{
Client();
return 0;
}
备忘录模式最常见的是用于游戏存档。
标签:code 游戏 tst bubuko delete 技术 private info block
原文地址:https://www.cnblogs.com/walkinginthesun/p/9558004.html