Use
Memo Mode (Memento) 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.
Memo mode is a behavioral pattern .
structure
Figure-Memo Pattern Structure chart
Memento: is responsible for storing the internal state of the originator object and can prevent objects other than originator from accessing the Memento.
Memento has two interfaces, caretaker can only see the narrow interface of the memo, and it can only pass the memo to other objects.
Originator can see a wide interface that allows it to access all the data needed to return to the previous state.
classMemento {
PrivateString State;
PublicMemento (String state) {
This. state = State;
}
PublicString GetState () {
returnState
}
}
Originator: Responsible for creating a memo Memento that records its internal state at the current moment and can use the memo to restore its internal state.
Originator can determine which internal states of the Memento storage originator as needed.
classOriginator {
PrivateString State;
PublicvoidSetState (String state) {
This. state = State;
}
PublicString GetState () {
returnState
}
PublicMemento Creatememento () {
return(NewMemento (state));
}
PublicvoidSetmemento (Memento Memento) {
state = Memento. GetState ();
}
PublicvoidShow () {
SYSTEM.OUT.PRINTLN ("state =" + state);
}
}
Caretaker: Responsible for keeping the memo Memento, unable to operate or check the contents of the memo.classCaretaker {
PrivateMemento Memento;
PublicvoidSetmemento (Memento Memento) {
This. Memento = Memento;
}
PublicMemento Getmemento () {
returnMemento
}
}
Test code
PublicclassMementopattern {
Public StaticvoidMain (string[] args) {
Originator o =NewOriginator ();
O.setstate ("on");
O.show ();
Caretaker C =NewCaretaker ();
C.setmemento (O.creatememento ());
O.setstate ("OFF");
O.show ();
O.setmemento (C.getmemento ());
O.show ();
}
}View Code
Run results
State = On
State = OFF
State = OnView Code
JAVA design Mode Memo mode