Overview
Capture the internal state of an object without compromising encapsulation, and save the state outside the object. In this way, the object can be restored to the previously saved state.
Applicability
1. You must save the (partial) state of an object at a certain time point so that it can be restored to the previous State only when necessary. 2. If an interface is used to directly obtain these States for other objects, the implementation details of the object will be exposed and the object encapsulation will be broken.
Participants
1. Memento memorandum stores the internal status of the primary object. 2. The originator generator creates a memorandum to record its internal state at the current time. Use the memorandum to restore the internal state. 3. Caretaker is responsible for saving the memorandum. The content of the memorandum cannot be operated or inspected.
Class Diagram
Example
Package COM. sql9.actioned;/*** memorandum mode example * @ author iihero **/class memento {private string State; public memento (string state) {This. state = State;} Public String getstate () {return state;} public void setstate (string state) {This. state = State ;}} class originator {private string state; Public String getstate () {return state;} public void setstate (string state) {This. state = State;} public memento creatememento () {return new memento (State);} public void setmemento (memento) {state = memento. getstate ();} public void showstate () {system. out. println (state) ;}} class caretaker {private memento; Public memento getmemento () {return this. memento;} public void setmemento (memento) {This. memento = memento;} public class mementotest {public static void main (string [] ARGs) {originator org = new originator (); Org. setstate ("meeting"); caretaker CTK = new caretaker (); CTK. setmemento (Org. creatememento (); // encapsulate data in caretaker Org. setstate ("sleeping"); Org. showstate (); // display Org. setmemento (CTK. getmemento (); // re-import the data. The Org is lost in the "meeting" status. showstate ();}}
Result
Sleeping
Meeting