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
The memorandum stores the internal status of the primary object.
2. Originator
The primary machine creates a memorandum to record its internal state at the current time.
Use the memo to restore the internal status.
3. Caretaker
Saves memos.
The content of the memorandum cannot be operated or inspected.
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 memento ){
State = memento. getState ();
}
Public void showState (){
System. out. println (state );
}
}
Class Caretaker {
Private Memento memento;
Public Memento getMemento (){
Return this. memento;
}
Public void setMemento (Memento 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. createmento (); // encapsulate data in Caretaker
Org. setState ("sleeping ");
Org. showState (); // display
Org. setMemento (ctk. getMemento (); // re-import the data. The original status "in the meeting" is lost.
Org. showState ();
}
}
Result
Sleeping
Meeting