int main(int argc, char* argv[]) { Originator* o = new Originator(); o->SetState("old"); //±¸Íüǰ״̬ o->PrintState();//ÏÔʾµ±Ç°Öµ Memento* m1 = o->CreateMemento(); //½«µ±Ç°×´Ì¬±¸Íü cout<<endl; o->SetState("newA"); //ÐÞ¸Ä״̬ o->PrintState(); cout<<endl; o->SetState("newB"); //ÐÞ¸Ä״̬ o->PrintState(); cout<<endl; o->SetState("newC"); //ÐÞ¸Ä״̬ o->PrintState(); Memento* m2 = o->CreateMemento(); //½«µ±Ç°×´Ì¬±¸Íü cout<<endl; o->RestoreToMemento(m1); //»Ö¸´ÐÞ¸Äǰ״̬ o->PrintState(); cout<<endl; o->RestoreToMemento(m2); //»Ö¸´ÐÞ¸Äǰ״̬ o->PrintState(); // printf("Hello World!\n"); return 0; }
///Memento 模式的关键就是要在不破坏封装行的前提下,捕获并保存一个类的内部 状态,这样就可以利用该保存的状态实施恢复操作。为了达到这个目标,可以在后面的实现 中看到我们采取了一定语言支持的技术。 ///在 Command 模式中,Memento 模式经常被用来维护可以撤销(Undo)操作的状态 void MementoTest() { Originator* o = new Originator(); o->SetState("old"); //备忘前状态 o->PrintState(); Memento* m = o->CreateMemento();//将状态备忘 o->SetState("new"); //修改状态 o->PrintState(); o->RestoreToMemento(m); //恢复修改前状态 o->PrintState(); }
int main(int argc,char* argv[]) { Originator* o = new Originator(); o->SetState("old"); //±¸Íüǰ״̬ o->PrintState(); Memento* m = o->CreateMemento(); //½«×´Ì¬±¸Íü o->SetState("new"); //ÐÞ¸Ä״̬ o->PrintState(); o->RestoreToMemento(m); //»Ö¸´ÐÞ¸Äǰ״̬ o->PrintState(); return 0; }
void test_memento() { Originator* o = new Originator; o->SetState("old"); o->PrintState(); Memento* m = o->CreateMemento(); //备忘当前状态 o->SetState("new"); o->PrintState(); o->RestoreToMemento(m); //恢复状态 o->PrintState(); delete o; }
int main() { // 创建一个原发器 Originator* pOriginator = new Originator("old state"); pOriginator->PrintState(); // 创建一个备忘录存放这个原发器的状态 Memento *pMemento = pOriginator->CreateMemento(); // 更改原发器的状态 pOriginator->SetState("new state"); pOriginator->PrintState(); // 通过备忘录把原发器的状态还原到之前的状态 pOriginator->RestoreState(pMemento); pOriginator->PrintState(); delete pOriginator; delete pMemento; return 0; }