Vii. Memo mode Memento (behavioral mode)

Source: Internet
Author: User

The purpose is to not violate the packaging principle. Collects and backs up an object's internal state so that the object can revert to a previous state later.


in Memento mode, the following roles are available: 1.Memento (Memo)* Store the internal state of the originator. Depending on the needs of the originator. You can store arbitrary internal states.* Protect access to the state. In addition to the originator object, other objects cannot access their stored internal state. The Memeoto actually provides 2 interfaces.caretaker can only access Memento's narrow interface (narrow interface)-it can only pass memento to other objects.instead, originator can access the memento's wide interface (wide interface). This interface allows the originator to get enough information to revert to the previous state. Ideally, Only originator that create memento have permission to access memento internal state information. 2.Originator (initiator)* You can create a new memento and store your current state information in Memento* can use memento to restore its internal status information 3.Caretaker (Responsible person)* Responsible for maintaining and managing memento objects* never operate or test the contents of Memento


Operation procedure of Memo mode
1. The client creates a memo object for the initiator role.
2, call the initiator object of an operation, this operation can be revoked.
3, check the validity of the status of the initiator object. The method of checking can be an internal self-examination of the initiator object, or it can be checked by an external object.
4, if necessary, the initiator's operation is revoked, that is, according to the memo object record, the initiator object's state recovery.

"If" protocol mode operation process:
1. Make a copy of the initiator object.
2. Perform an operation on the copy.
3, check whether the status of this copy is valid and self-just.
4, if the test results are invalid or not self-proper, then throw away the copy, and trigger the exception handler; Conversely, if the check is valid and self-executing, perform this operation on the original object
Obviously, this approach is a prudent and effective way to undo an operation and restore a more complex and difficult initiator object before the operation.

"If" the advantages and disadvantages of the protocol model
specifically, the advantage of this approach is to ensure that the initiator object will never be in an invalid or not self-consistent state, the disadvantage is that the successful operation must be executed two times.
if the success rate of the operation is lower, it is more cost-effective, but not very cost-effective.


advantages and disadvantages of using memo mode
I. Advantages of the MEMO model
1, sometimes the internal information of some initiator object must be kept outside the initiator object, but must be read by the initiator object, at this time,
using the memo mode, the complex initiator's internal information can be shielded from other objects, so that the encapsulated boundaries can be properly maintained.
2. This model simplifies the initiation of human beings. The initiator no longer needs to manage and save a version of its internal state, and clients can manage their own
The version of these states to be.
3, when the status of the initiator role changes, it is possible that the state is invalid, this time you can use the temporarily stored memo to restore the state.
Ii. shortcomings of the memo model:
1. If the status of the initiator role needs to be stored completely in the memo object, the memo object will be expensive on resource consumption.
2. When the responsible person stores a memo, the person in charge may not know how much storage space the state occupies and cannot
reminds the user whether an operation is expensive. 882--p
3, when the status of the initiator role changes, it is possible that this agreement is invalid. If the success rate of state change is not high, it is better to take the "if" protocol mode.

(1) Wide Interface and white box:
public class Client {   private static originator originator = new originator ();   private static Caretaker C = new caretaker ();   public static void Main (string[] args) {      //The Initiator object's state      originator.setstate ("on");      Creates a memo object and stores the state of the initiator object      C.savememento (Originator.creatememento ());      Modifies the initiator object's state      originator.setstate ("Off");      Restores the status of the initiator object      Originator.restorememento (C.retrievememento ());}   }

//Initiator Role class Originator {private String state;   Factory method, return a new Memo object public Memento Creatememento () {Return to New Memento (state);   }//Restores the initiator to the state public void Restorememento (Memento Memento) {this.state = Memento.getstate () as recorded in the Memo object;   }//The value method of the state public String getState () {return this.state;      }//The assignment method for the status public void SetState (String-state) {this.state = states;   System.out.println ("Current state =" + this.state); }}
/* * Memo mode requires a memo object to provide two different interfaces: A wide interface is provided to the initiator object, and another narrow interface is provided to all other objects, including the owner object. * The wide interface allows the initiator to read all the data; The narrow interface only allows it to pass the memo object to other objects without seeing the internal data. *///Memo Role Class Memento {   private String state;   Public Memento (String state) {      this.state = state;   }   Public String getState () {      return this.state;   }   public void SetState (String state) {      this.state = state;   }}

/* * The owner role is responsible for saving the memo object, but never modifying (or even viewing) the contents of the memo object (a better implementation is that the owner object simply cannot read from the memo object to modify its contents) *///owner role class caretaker {   private Memento Memento;   Method of value of Memo public   Memento Retrievememento () {      return this.memento;   }   Method of assigning a memo public   void Savememento (Memento Memento) {      this.memento = Memento;   }}

the state of the initiator object is set to "on" (or any valid state) first, and a Memo object is created to store the state, and the initiator object State to "OFF" (or any state), and finally restores the initiator object to the state stored by the memo object, which is the "on" state (or the previousstored in any state)
The timing of the memo system operation is this:
(1) Set the status of the initiator object to "on".
(2) Call the Creatememento () method of the initiator role to create a memo object to store the state.
(3) store the memo object in the owner object.
the timing of the memo system recovery is this:
(1) Set the status of the initiator object to "OFF";
(2) Remove the object of the memorandum from the person in charge;
(3) Restores the initiator object to the state that the memo object is stored in, "on" state.
advantages and disadvantages of white box implementation
One obvious benefit of the white box implementation is that it is relatively simple and therefore often used for teaching purposes. One obvious drawback of the white box implementation is that it destroys the encapsulation of the initiator state.

(2) narrow Interface or black box implementation:
//client public   Class Client {private static originator originator = new originator ();   private static Caretaker C = new Caretaker ();      public static void Main (string[] args) {//The Initiator object's state originator.setstate ("on");      Creates a memo object and stores the state of the initiator object C.savememento (Originator.creatememento ());      Modifies the initiator object's state originator.setstate ("Off");   Restores the status of the initiator object Originator.restorememento (C.retrievememento ()); }}
Initiator Role class Originator {   private String state;   Public originator () {   }   //Factory method, return a new Memo object public   mementoif Creatememento () {      return new Memento ( this.state);   }   Restores the initiator to the memo object record state public   void Restorememento (Mementoif memento) {      Memento amemento = (memento) memento;      This.setstate (Amemento.getstate ());   }   Public String getState () {      return this.state;   }   public void SetState (String state) {      this.state = state;      SYSTEM.OUT.PRINTLN ("state =" + state);   }   Protected class Memento implements MEMENTOIF {      private String savedstate;      Public Memento (String somestate) {        this.savedstate = somestate;      }      private void SetState (String somestate) {        savedstate = somestate;      }      Private String getState () {        return savedstate;}}   }

Interface Mementoif {}

Memo role Class Memento implements MEMENTOIF {   private String state;   Public Memento (String state) {      this.state = state;   }   Public String getState () {      return this.state;   }   public void SetState (String state) {      this.state = state;   }}

Class Caretaker {   private mementoif memento;   Public Mementoif Retrievememento () {      return this.memento;   }   public void Savememento (Mementoif memento) {      this.memento = memento;   }}

The black box realizes the timing of the run time;
(1) Set the status of the initiator object to "on".
(2) Call the Creatememento () method of the initiator role to create a memo object to store the state.
(3) store the memo object in the owner object. Because the owner object gets only the Mementoif type, it cannot read the state inside the memo.
the timing of the recovery is:
(1) Set the status of the initiator object to "OFF";
(2) Remove the memo object from the owner object. Note that only the Mementoif interface can be obtained at this time, so the internal state of this object cannot be read out
(3) The state of the initiator object is restored to the state stored by the memo object, and the Mementoif interface is implemented because of the internal class memento of the initiator object.
this inner class is the true type of the incoming memo object, so the initiator object can read out the internal state of the object using the private interface of the inner class memento.

(3) A memo mode that stores multiple states:

Memo role Import Java.util.vector;public class memento{private Vector states;private int Index;//<span style= " font-size:14px; Font-family:arial, Helvetica, Sans-serif; The constructor of the > Memo clones the incoming states and then deposits the clone inside the memo object, which is an important detail, because if not, it will </span><pre title= "Memo (Memento pattern)" Behavior pattern First "" style= "FONT-SIZE:14PX;" The >     //will cause the client and the memo object to hold a reference to the same vector object, or to modify the vector object at the same time, causing the system to crash.
Public Memento (Vector states,int index) {this.states = (vector) states.clone (); this.index = index;} The state value method vector GetStates () {return states;} Checkpoint value method int GetIndex () {return this.index;}}

Responsible role import Java.util.vector;public class caretaker{private originator o;private vector mementos = new vector (); private int current;public caretaker (originator o) {this.o = O;current = 0;} public int Creatememento () {Memento Memento = O.creatememento (), mementos.addelement (Memento); return current + +;} Restore the initiator to a checkpoint public void Restorememento (int index) {Memento Memento = (Memento) mementos.elementat (index); O. Restorememento (memento);} A checkpoint removes the public void Removememento (int index) {mementos.removeelementat (index);}}

Client public class Client{private static originator o = new originator ();p rivate static caretaker C = new Caretaker (o);p UBL IC static void Main (string[] args) {//Change the status o.setstate ("state 0");//Create a checkpoint c.creatememento ();//Change the State o.setstate ("1" ); C.creatememento (); O.setstate ("State 2"), C.creatememento (); O.setstate ("State 3"); C.creatememento (); O.setstate (" State 4 "); C.creatememento (); o.printstates ();//revert to a second checkpoint System.out.println (" Restoring to 2 "); C.restorememento (2); O . Printstates (); System.out.println ("Restoring to 0"); c.restorememento (0); O.printstates (); System.out.println ("Restoring to 3"); C.restorememento (3); O.printstates ();}}

(4) Readme history mode (a variant of memo mode)
since the "Readme history" as a special form of implementation of a memo pattern is very simple and understandable, it is probably the most popular form of implementation of the memo pattern.
Narrow interface public Interface mementoif{}

Initiator role public class Originator{public String state;public originator () {}public void changestate (String state) { This.state = State; SYSTEM.OUT.PRINTLN ("state had been changed to:" + state);} Public Memento Creatememento () {Return to New Memento (this);} public void Restorememento (Mementoif memento) {Memento m = (memento) memento;changestate (m.state);} Class Memento implements Mementoif{private string State;private string GetState () {return state;} Private Memento (originator o) {this.state = O.state;}}}

Client public class Client{private static originator o;private static mementoif memento;public static void main (String args[ ] {o = new originator (); O.changestate ("State 1"), Memento = O.creatememento (); O.changestate ("State 2"); O. Restorememento (memento);}}







Vii. Memo mode Memento (behavioral mode)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.