知识点
备忘录(memento)、token
知识内容
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
示例
#include<iostream>
using namespace std;
class Memento
{
private:
int state;
public:
Memento(int myState):state(myState){}
int GetState()
{
return this -> state;
}
void SetState(int myState)
{
this -> state = myState;
}
};
class Originator
{
private:
int state;
public:
Memento* CreateMemento()
{
cout << "save state..." << endl;
Memento* memento = new Memento(state);
return memento;
}
void SetMemento(Memento* m)
{
cout << "restore state..." << endl;
this -> state = m -> GetState();
}
int GetState()
{
return this -> state;
}
void SetState(int myState)
{
this -> state = myState;
}
};
int main()
{
Originator* originator = new Originator();
cout << "current state:" << originator -> GetState() << endl;
Memento* memento = originator -> CreateMemento();
int state = 100;
originator -> SetState(100);
cout << "current state:" << originator -> GetState() << endl;
originator -> SetMemento(memento);
cout << "current state:" << originator -> GetState() << endl;
return 0;
}
链接
https://github.com/xierensong/learngit/blob/master/DPattern/17/1.cpp