Memo Mode (Memento) definition
captures the internal state of an object without compromising encapsulation, and saves the state outside that object. You can then revert the object back to the previously saved state.
UML diagram
Role Description Memo (Memento) role
(1) Store the Civil War state of the initiator (originator) object. A memo can determine the internal state of how many initiator (originator) objects are stored based on the decision of the initiator object.
(2) A memo can protect its content from being read by any object other than the initiator (originator) object.
Sponsor
Originator) role
(1) Create a Memo object that contains the current internal state.
(2) Use the memo object to store its internal state.
Head
Caretaker) role
(1) Responsible for saving the memorandum object.
(2) Do not check the contents of the memo object.
Example
Initiator role
PackageCom.csdhsm.pattemdesign.memento;/*** @Title: Originator.java * @Description: Sponsor class *@author: Han * @date: June 25, 2016 PM 8:26:03*/ Public classOriginator {PrivateString State; PublicString getState () {returnState ; } Public voidsetState (String state) { This. State =State ; } PublicMemento Creatememento () {return NewMemento (state); } Public voidSetmemento (Memento Memento) { state=memento.getstate (); } Public voidShow () {System.out.println ("State" +State ); }}
Memo Class
PackageCom.csdhsm.pattemdesign.memento;/*** @Title: Memento.java * @Description: Memo class *@author: Han * @date: June 25, 2016 PM 8:26:26*/ Public classMemento {PrivateString State; PublicMemento (String state) { This. State =State ; } PublicString getState () {returnState ; }}
Manager class
PackageCom.csdhsm.pattemdesign.memento;/*** @Title: Caretaker.java * @Description: Manager class *@author: Han * @date: June 25, 2016 PM 8:27:30*/ Public classCaretaker {PrivateMemento Memento; PublicMemento Getmemento () {returnMemento; } Public voidSetmemento (Memento Memento) { This. Memento =Memento; }}
Client
PackageCom.csdhsm.pattemdesign.memento; Public classSolution { Public Static voidMain (string[] args) {originator O=Neworiginator (); //originator initial state, state property is "on"O.setstate ("On"); O.show (); Caretaker C=Newcaretaker (); //to back up the stateC.setmemento (O.creatememento ()); //status change to OFFO.setstate ("Off"); O.show (); O.setmemento (C.getmemento ()); O.show (); }}
Results
OK, Success!
Summarize
Advantages of Memo mode:
(1) The object state is backed up to facilitate state rollback in the event of an unexpected occurrence.
(2) A copy of the object state is managed by the manager (caretaker), and the initiator does not need to manage the state of the backup. While in the restore state, the initiator's own state restore method, the outside world can not obtain the sponsor's backup status information to ensure the security of the backup data.
Cons of Memo mode:
Backing up an object state consumes more system resources.
Design Pattern-----Memo Mode