代码:
#include <iostream>
#include <string>
using namespace std;
//保存要备忘的状态
class Memento {
private:
string state;
public:
Memento()
{
state = "";
}
Memento(string m_state):state(m_state){}
string getState() {
return state;
}
void setState(string state) {
this->state = state;
}
};
//需要备忘的对象
class Originator {
private :
string state;
public:
Originator()
{
state = "";
}
string getState() {
return state;
}
void setState(string state) {
this->state = state;
}
//save之后并返回状态
Memento saveMemento(){
return Memento(this->state);
}
void loadMemento(Memento memento){
this->setState(memento.getState());
}
};
//备忘管理者
class Caretaker {
private :
Memento memento;
public :
//get之后返回
Memento getMemento(){
return memento;
}
void setMemento(Memento memento){
this->memento = memento;
}
};
int main (int argc, char *argv[])
{
Originator originator;
originator.setState("状态1");
cout<<"初始状态:"<<originator.getState()<<endl;
Caretaker caretaker;
caretaker.setMemento(originator.saveMemento());
originator.setState("状态2");
cout<<"改变后状态:"<<originator.getState()<<endl;
originator.loadMemento(caretaker.getMemento());
cout<<"恢复后状态:"<<originator.getState()<<endl;
}
编译&运行:
ngnsvr9 [** NONE **]/home/xionghailong/demo/mement $ g++ main.cpp -o main
ngnsvr9 [** NONE **]/home/xionghailong/demo/mement $ ./main
初始状态:状态1
改变后状态:状态2
恢复后状态:状态1