备忘录模式:属于行为型模式基本原理:保存一个对象的某个状态,以便在适当的时候恢复对象。主要流程: 1.创建一个状态对象 2.创建管理类,用来管理状态对象,支持修改状态和得到状态 3.创建存储类,用来存储当前的状态对象,支持存储和获得对象
#include <iostream> #include <string> #include <vector> using namespace std; //对象 class Memento { public: string state; Memento(string state) { this->state = state; } string getState() { return this->state; } }; //管理对象 class Originator { public: string state; void setState(string state) { this->state = state; } string getState() { return this->state; } Memento *saveStateToMemento() { return new Memento(this->state); } void getStateFromMemento(Memento *memento) { this->state = memento->getState(); } }; //存储对象 class CareTaker { private: vector<Memento*> mementoList; public: void add(Memento *state) { mementoList.push_back(state); } Memento *get(int index) { if(index < mementoList.size()) { return mementoList[index]; } return NULL; } }; int main() { Originator *originator = new Originator(); CareTaker *careTaker = new CareTaker(); originator->setState("State #1"); originator->setState("State #2"); careTaker->add(originator->saveStateToMemento()); originator->setState("State #3"); careTaker->add(originator->saveStateToMemento()); originator->setState("State #4"); cout<<"show save all state:"<<endl; for(int i=0;i<4;i++) { if(careTaker->get(i)) { cout<<" i = "<<i<<" : "<<careTaker->get(i)->getState()<<endl; } } cout<<endl; cout<<"now state : "<<originator->getState()<<endl; cout<<endl; cout<<"change state to 0"<<endl; originator->getStateFromMemento(careTaker->get(0)); cout<<"now state : "<<originator->getState()<<endl; return 0; }