Originator(原生者)
需要被保存状态以便恢复的那个对象。
Memento(备忘录)
该对象由Originator创建,用来保存Originator的内部状态
Caretaker(管理者)
负责在适当的时间保存/恢复Originator对象的状态
适用于:
在不破坏疯转的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样就可以将以后的对象状态恢复到之前保存的状态。
适用于功能比较复杂的,但是需要记录或者维护属性历史的类;或者需要保存的属性只是众多属性中的一小部分时Originator可以根据保存的Memento还原到前一个状态。
结构图:
需求:
现有一个男孩,没有追妹子前元气满满,但是和妹子表白后,很难受,通过备忘录恢复后又变的元气满满。
class Originator;
class Memento{
private:
string state;
friend class Originator;
Memento(string state){
this->state = state;
}
};
class Originator{
private:
string state;
public:
void setState(string state){
this->state = state;
}
Memento* creatMemento(){
return new Memento(state);
}
void reStoreMemento(Memento *memo){
state = memo->state;
}
void show(){
cout << "当前状态:" << state << endl;
}
};
class CareTaker{
private:
vector<Memento*> vec;
public:
void setMemento(Memento *m){
vec.push_back(m);
}
Memento* getMemento(int index){
vector<Memento*>::iterator it;
it = vec.begin();//集合下标从1开始
it += index - 1;
return *it;
}
};
客户端:
int main(void){
Originator *po = new Originator();
po->setState("没有追妹子前元气满满");
po->show();
CareTaker *pc = new CareTaker();
pc->setMemento(po->creatMemento());
po->setState("表白被拒难受的一批");
po->show();
pc->setMemento(po->creatMemento());
po->reStoreMemento(pc->getMemento(1));
po->show();
system("pause");
return 0;
}
调试效果: