The main purpose is to save a certain state of an object, in order to restore the object at the appropriate time, the individual think that the backup mode is more image, popular: Assume that there are various properties in the original class A,a, a can determine the properties to be backed up, Memo Class B is used to store a some of the internal state, Class C, is a store for the memo, and can only be stored, can not be modified and other operations. Make a diagram to analyze
The original class is the original class, which has the property value to save and a memo class to hold the value. The Memento class is a memo class, and the storage class is the class that stores the memo, holding an instance of the Memento class, which is well understood. Direct View Source:
Package Mementotest;public class Original {private string value;public void SetValue (String value) {This.value=value;} Public String GetValue () {return this.value;} Public Original (String value) {This.value=value;} Create Memo public Memento Creatememento () {///creates a value of values as passed in to return new Memento (value);} public void Restorememento (Memento Memento) {this.value=memento.getvalue ();}}
Package Mementotest;public class Memento {private string Value;public Memento (String value) {This.value=value;} public void SetValue (String value) {This.value=value;} Public String GetValue () {return this.value;}}
Package Mementotest;public class Storage {//has a Memento instance, after all it is only responsible for handling memo storage private Memento memento;public Storage (Memento Memento) {this.memento = memento;} public void Setmemento (Memento Memento) {this.memento = Memento;} Public Memento Getmemento () {return Memento;}}
Test class:
Package Mementotest;public class Test {public static void main (string[] args) {//Create original class Original Origi = new Original ("egg" );//create memo Storage storage = new Storage (Origi.creatememento ());//Modify the state of the original class SYSTEM.OUT.PRINTLN ("Initialize state:" + Origi.getvalue ()); Origi.setvalue ("Niu"); SYSTEM.OUT.PRINTLN ("Modified State is:" + origi.getvalue ());//reply to the original class's State Origi.restorememento (Storage.getmemento ()); System.out.println ("Post-Restore Status:" + Origi.getvalue ());}}
Test results:
The initialization status is: Egg
The modified state is: NIU
The status after recovery is: egg
Simple description: When the original class is created, value is initialized to egg, modified, the value of value is set to Niu, and the last penultimate row is restored, and the result is successfully restored. In fact, I think this mode is called "Backup-Restore" mode most image.
Memo Mode (Memento)