Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/45600505
I. Overview
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.
Second, applicability
1. You must save the state of an object at a certain point in time so that it can revert back to its previous state if it is needed later.
2. If an interface is used to get these states directly from other objects, it exposes the implementation details of the object and destroys the encapsulation of the object.
Third, participants
The 1.Memento memo stores the internal state of the original sender object.
2.Originator The generator creates a memo that records its internal state at the current moment. Use Notes to restore internal status.
3.Caretaker is responsible for keeping memos. The contents of the memo cannot be manipulated or checked.
Four, class diagram
V. Examples
Memento
Package com.lyz.design.memento;/** * Memento * @author Liuyazhuang * */public class Caretaker { private memento me Mento; Public Memento Getmemento () { return this.memento; } public void Setmemento (Memento Memento) { this.memento = Memento; }}
Originator
Package com.lyz.design.memento;/** * Originator * @author Liuyazhuang * */public class Memento { private String s Tate; Public Memento (String state) { this.state = state; } Public String getState () { return state; } public void SetState (String state) { this.state = state; }}
Caretaker
Package com.lyz.design.memento;/** * Caretaker * @author Liuyazhuang * */public class Originator { private String State; Public String getState () { return state; } public void SetState (String state) { this.state = state; } Public Memento Creatememento () { return to new Memento (state); } public void Setmemento (Memento Memento) {state = Memento.getstate (); } public void Showstate () { System.out.println (state); }}
Test
Package com.lyz.design.memento;/** * Test * @author Liuyazhuang * */public class Test {public static void main (St Ring[] args) { originator org = new originator (); Org.setstate ("in-session"); Caretaker CTK = new Caretaker (); Ctk.setmemento (Org.creatememento ());//Encapsulate data in caretaker org.setstate ("sleeping"); Org.showstate ();//Display Org.setmemento (Ctk.getmemento ());//re-import data into org.showstate ();} }
result
Sleep in the meeting
On the Java design Pattern--Memo mode (Memento)