DesignPattern/19.MementoPattern/2.Code/demo.h

90 lines
1.3 KiB
C
Raw Normal View History

2019-11-05 14:47:55 +00:00
#ifndef __DEMO_H__
#define __DEMO_H__
#ifndef __DEMO_H__
// ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class Memento;
// ԭ<><D4AD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>ʵ<EFBFBD><CAB5>
class Originator
{
public:
Originator(){
state = "";
}
Originator(String iState){
state = iState;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>¼<EFBFBD><C2BC><EFBFBD><EFBFBD>
Memento* createMemento(){
return new Memento(this);
}
// <20><><EFBFBD>ñ<EFBFBD><C3B1><EFBFBD>¼<EFBFBD><C2BC><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD>ԭ<EFBFBD><D4AD><EFBFBD><EFBFBD>״̬
void restoreMemento(Memento* m){
state = m->getState();
}
void setState(string iState){
state = iState;
}
string getState(){
return state;
}
private:
string state;
};
// <20><><EFBFBD><EFBFBD>¼ <20><><EFBFBD><EFBFBD>ʵ<EFBFBD>֣<EFBFBD><D6A3><EFBFBD><EFBFBD><EFBFBD>ԭ<EFBFBD><D4AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ƣ<EFBFBD>
class Memento
{
public:
Memento(){
state = "";
}
Memento(Originator* o){
state = o->getState();
}
void setState(String iState){
state = iState;
}
string getState(){
return state;
}
private:
String state;
};
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>ʵ<EFBFBD><CAB5>
class Caretaker
{
public:
Caretaker(){}
Memento* getMemento(){
return memento;
}
void setMemento(Memento *m){
memento = m;
}
private:
Memento* memento;
};
// <20>ͻ<EFBFBD><CDBB><EFBFBD> ʾ<><CABE><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int main()
{
// <20><><EFBFBD><EFBFBD>ԭ<EFBFBD><D4AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
Originator o = new Originator("״̬1");
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˶<EFBFBD><CBB6><EFBFBD>
Caretaker *c = new Caretaker();
c->setMemento(o->createMemento());
o->setState("״̬2");
// <20>Ӹ<EFBFBD><D3B8><EFBFBD><EFBFBD>˶<EFBFBD><CBB6><EFBFBD><EFBFBD><EFBFBD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>¼<EFBFBD><C2BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʵ<EFBFBD>ֳ<EFBFBD><D6B3><EFBFBD>
o->restoreMemento(c->getMemento());
return 0;
}
#endif
#endif // __DEMO_H__