Memento Pattern saves a state of an object to restore the object when appropriate. The memo mode is a behavioral mode.
Intent: Captures the internal state of an object without destroying encapsulation and saves the state outside of the object.
Main solution: The so-called memo mode captures the internal state of an object without destroying the package, and saves the state outside the object, so that the object can be restored later. The state that was originally saved.
When to use: Many times we always need to record the internal state of an object. The purpose of this is to allow the user to cancel the indeterminate or erroneous operation and return to his original state. So that he has "regret medicine" to eat.
How to fix: Specially store object state through a memo class.
Key Code: The client is not coupled to the memo class and is coupled to the memo management class.
Application example: 1. Regret medicine. 2. Archive when playing games. 3. ctri + z in Windows. 4. Backward in IE. 4. Database transaction management.
Advantages: 1. Provide the user with a mechanism to restore the state, which allows the user to return to a historical state more conveniently. 2. The encapsulation of information is implemented so that the user does not need to care about the preservation details of the state.
Disadvantages: Consume resources. If the class has too many member variables, it will inevitably occupy a relatively large resource, and each save will consume a certain amount of memory.
Usage scenarios: 1. Relevant status scenarios where data needs to be saved/restored. 2. Provide a rollback operation.
Note: 1. In order to comply with the Dimit principle, a class of management memoranda is also added. 2. In order to save memory, you can use the prototype mode + memo mode.
The memo mode uses three classes Memento, Originator, and CareTaker. Memento contains the state of the object to be restored. The Originator creates and stores the state in the Memento object. The Caretaker object is responsible for restoring the state of the object from Memento.
MementoPatternDemo, our demo class uses CareTaker and Originator objects to display the state recovery of an object.
Create a Memento class.
Create the Originator class.
Create a CareTaker class.
Use the CareTaker and Originator objects.
Verify the output.re class="result prettyprint prettyprinted" style="">Current State: State #4 First saved State: State #2 Second saved State: State #3