The memo mode of Java design mode

Source: Internet
Author: User

This paper continues the memo mode of 23 design pattern series.
When we are programming, we often need to save the middle state of the object, and when necessary, we can revert to this state. For example, when we are programming with eclipse, if we write a mistake (such as accidentally accidentally deleting a few lines of code), we want to return to the state before deletion, we can use CTRL + Z to return. When you are chess, you can back off. At this point we can use the memo mode to achieve.
definitioncaptures the internal state of an object without compromising encapsulation, and saves the state outside that object. This allows the object to be restored to its previously saved state
role Sponsor:Records the internal state of the current moment and is responsible for defining which state is part of the backup scope and responsible for creating and recovering Memo data. Memo: responsible for storing the internal state of the initiator object, providing the internal state required by the initiator when needed. Administrative roles: manage memos, save and provide memos.
Application
Class Originator {private String state = "";      Public String GetState () {return state;      public void SetState (String state) {this.state = state;      } public Memento Creatememento () {return new Memento (this.state);      } public void Restorememento (Memento Memento) {this.setstate (Memento.getstate ());      }} 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 Caretaker {private Memento Memento;      Public Memento Getmemento () {return Memento;      } public void Setmemento (Memento Memento) {this.memento = Memento; }} public class Client {public static void main (string[] args) {Originator originator = new Originator ()          ; Originator.setstaTe ("State 1");          SYSTEM.OUT.PRINTLN ("Initial state:" +originator.getstate ());          Caretaker caretaker = new Caretaker ();          Caretaker.setmemento (Originator.creatememento ());          Originator.setstate ("State 2");          SYSTEM.OUT.PRINTLN ("changed state:" +originator.getstate ());          Originator.restorememento (Caretaker.getmemento ());      System.out.println ("Post-Restore Status:" +originator.getstate ());   }  }

The code shows an example of a single-state single-backup, which is very simple: the originator class has to be backed up by a status variable in order to be restored when needed; in the memento class, there is a Used to store the temporary state of the originator class in a state variable, while the caretaker class is used to manage the memo class to write to or retrieve state from the memo object.

Multi-State multi-backup memo

In the example of a generic code demonstration, the originator class has only one state variable that needs to be backed up, and typically, the initiator role is usually a javabean, with more than one variable in the object that needs to be backed up, and more than one backup, which is a multi-state multi-backup memo. There are many ways to implement a memo, the memo pattern has a lot of deformation and processing methods, such as general code in a way that is generally not used, in most cases, the memo mode is multi-state multi-backup. In fact, multi-state multi-backup is also very simple, the most common method is that we add a map container in the memento to store all the state, in the caretaker class also use a map container to store all the backups. Here we give an example of a multi-state multi-backup:

Class Originator {private String state1 = "";      Private String State2 = "";        Private String State3 = "";      Public String getState1 () {return state1;      } public void SetState1 (String state1) {this.state1 = state1;      } public String GetState2 () {return state2;      } public void SetState2 (String state2) {this.state2 = State2;      } public String GetState3 () {return state3;      } public void SetState3 (String state3) {this.state3 = State3;      } public Memento Creatememento () {Return to New Memento (Beanutils.backupprop (this));      } public void Restorememento (Memento Memento) {Beanutils.restoreprop (this, Memento.getstatemap ());      The public String toString () {return "state1=" +state1+ "state2=" +state2+ "state3=" +STATE3;            }} class Memento {Private map<string, object> Statemap; Public Memento (map<string, OBject> map) {this.statemap = map;      } public map<string, Object> Getstatemap () {return statemap;      } public void Setstatemap (map<string, object> statemap) {this.statemap = Statemap; }} class Beanutils {public static map<string, object> Backupprop (Object Bean) {map<string, obje          ct> result = new hashmap<string, object> ();              try{BeanInfo BeanInfo = Introspector.getbeaninfo (Bean.getclass ());              propertydescriptor[] descriptors = beaninfo.getpropertydescriptors ();                  for (PropertyDescriptor des:descriptors) {String fieldName = Des.getname ();                  Method getter = Des.getreadmethod ();                  Object fieldvalue = Getter.invoke (Bean, New object[]{});                  if (!fieldname.equalsignorecase ("class")) {Result.put (fieldName, fieldvalue);                   }              }     }catch (Exception e) {e.printstacktrace ();      } return result; public static void Restoreprop (Object bean, map<string, object> PropMap) {try {B              Eaninfo beanInfo = Introspector.getbeaninfo (Bean.getclass ());              propertydescriptor[] descriptors = beaninfo.getpropertydescriptors ();                  for (PropertyDescriptor des:descriptors) {String fieldName = Des.getname ();                      if (Propmap.containskey (FieldName)) {Method setter = Des.getwritemethod ();                  Setter.invoke (Bean, New Object[]{propmap.get (FieldName)});          }}} catch (Exception e) {e.printstacktrace ();      }}} class caretaker {private map<string, memento> memmap = new hashmap<string, memento> ();      Public Memento Getmemento (String index) {return memmap.get (index); } public VOID Setmemento (String index, Memento Memento) {this.memMap.put (index, Memento);          }} class Client {public static void main (string[] args) {originator Ori = new originator ();          Caretaker caretaker = new Caretaker ();          Ori.setstate1 ("China");          Ori.setstate2 ("Mighty");          Ori.setstate3 ("prosperity");                    System.out.println ("= = = Initialize state ===\n" +ori);          Caretaker.setmemento ("001", Ori.creatememento ());          Ori.setstate1 ("Software");          Ori.setstate2 ("Architecture");          Ori.setstate3 ("excellent");                    System.out.println ("= = = Modified state ===\n" +ori);          Ori.restorememento (Caretaker.getmemento ("001"));      System.out.println ("= = = Recovery after state ===\n" +ori);  }  } 


SummaryAdvantages1, when the status of the initiator role changes, it is possible that this is a wrong change, we use the memo mode can be used to restore the wrong change. 2. The status of the backup is stored outside the initiator role, so that the initiator role does not need to manage the status of each backup. Disadvantages1, in the actual application, the memo mode is multi-state and multi-backup, the status of the initiator role needs to be stored in the memo object, the consumption of resources is more serious. 2. If there is a need to provide rollback operations, the use of Memo mode is very suitable, such as JDBC transaction operations, text editor CTRL + Z recovery.
More Design Patterns:23 design Mode series

jason0539

Blog: http://blog.csdn.net/jason0539 (reprint please indicate the source)

Recommended sweep code pay attention to the public number, to add color to life

The memo mode of Java design mode

Related Article

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.