First, the definition
captures the internal state of an object without compromising encapsulation, and saves the state outside that object. This allows the object to be restored to its previously saved state
Second, examples
2.1 Initiator: records the internal state of the current moment and is responsible for defining which state is part of the backup scope and responsible for creating and recovering Memo data.
Public classOriginator {Private stringState =string. Empty; Public stringGetState () {returnState ; } Public voidSetState (string_state) { state=_state; } PublicMemento Creatmemento () {return NewMemento (state); } Public voidRestorememento (Memento _memento) {SetState (_memento. GetState ()); } }
2.2 Memo: responsible for storing the internal state of the initiator object, providing the internal state required by the initiator when needed.
Public classMemento {Private stringState =string. Empty; PublicMemento (string_state) { state=_state; } Public stringGetState () {returnState ; } Public voidSetState (string_state) { state=_state; } }
2.3 Management Role: manage memos, save and provide memos.
Public class Caretaker { private Memento Memento; Public void Setmemento (Memento _memento) { = _memento; } Public Memento Getmemento () { return memento; } }
2.4 Client:
//-------------------------Memo Mode---------------------Memento.originator originator =NewMemento.originator (); Originator. SetState ("Initial State -1"); Console.WriteLine ("Initial state: {0}", originator. GetState ()); //Memo StatusMemento.caretaker caretaker =NewMemento.caretaker (); Caretaker. Setmemento (originator. Creatmemento ()); //Modify StatusOriginator. SetState ("Status -2"); Console.WriteLine ("Modify Status: {0}", originator. GetState ()); //Recovery Statusoriginator. Restorememento (caretaker. Getmemento ()); Console.WriteLine ("post-Restore status: {0}", originator. GetState ()); Console.readkey ();
Results:
Iii. Summary
Excellent:
- When the status of the initiator role changes, it is possible that this is a wrong change, we can use the memo mode to restore the error.
- The status of the backup is saved outside the initiator role, so that the initiator role does not need to manage the status of each backup.
Lack:
- In practical applications, the memo mode is multi-state and multi-backup, the status of the initiator role needs to be stored in the memo object, the consumption of resources is more serious.
Design mode (19): Memo Mode