Memo Mode (Memento): captures the internal state of an object without compromising encapsulation, and saves the state outside that object. The object can then be restored to its previously saved state.
Pattern implementation:
[Code]struct state{wchar_t wcsstate[260];}; Class Memento{public:memento (state *pstate): M_pstate (pState) {} state *getstate () {return m_pstate;} Private:friend class originator; State *m_pstate;}; Class Originator{public:originator (): M_pstate (NULL) {} ~originator () {//delete The storage of the state if (m_pstate) {delete m_pstate; M_pstate = NULL; }} void Setmemento (Memento *pmemento); Memento * Creatememento (); void SetValue (wchar_t *val) {memset (wcsvalue, 0, 260 * sizeof (wchar_t)); wcscpy_s (Wcsvalue, 260, Val); } void Printstate () {std::wcout << wcsvalue << Std::endl;} private:state *m_pstate; To store the object's state wchar_t wcsvalue[260]; This is the object's real data}; Memento *originator::creatememento () {m_pstate = new State; if (m_pstate = = null) return null; Memento *pmemento = new Memento (m_pstate); wcscpy_s (M_pstate->wcsstate, 260, Wcsvalue); Backup the value return pmemento;} void Originator::setmemento (Memento *pmemento) {m_pstate = Pmemento->getstate (); Recovery the Data memset (wcsvalue, 0, 260 * sizeof (wchar_t)); wcscpy_s (Wcsvalue, 260, m_pstate->wcsstate);} Manager the Mementoclass caretaker{public:memento *getmemento () {return m_pmemento;} void Setmemento (Memento *pmemento) {//free The previous Memento if (m_pmemento) {Delete M_pmemento ; M_pmemento = NULL; }//set the new Memento m_pmemento = Pmemento; }private:memento *m_pmemento;};
Client:
[Code]int Main () { Originator *poriginator = new originator (); Poriginator->setvalue (L "on"); Poriginator->printstate (); Output:on //now I backup the state caretaker *pcaretaker = new Caretaker (); Pcaretaker->setmemento (Poriginator->creatememento ()); Set the new state Poriginator->setvalue (L "off"); Poriginator->printstate (); Output:off//recovery to the old State Poriginator->setmemento (Pcaretaker->getmemento ()); Poriginator->printstate (); Output:on if (pcaretaker) delete pcaretaker; if (poriginator); Delete Poriginator; return 0;}
The above is the C + + design mode of understanding the content of the memo mode, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!