23 Design Modes (15): Memo Mode

Source: Internet
Author: User

Definition: captures 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

Type: Behavior class pattern.

Class Diagram:

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. At this point we can use the memo mode to achieve.

Structure of the memo pattern:

Initiator: 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.

Common Code implementations:

Class Originator {Private String state = "";Public StringGetState () {return state; }PublicvoidSetState (String state) {This.state = State; }Public MementoCreatememento () {ReturnNew Memento (This.state); }PublicvoidRestorememento (Memento Memento) {This.setstate (Memento.getstate ()); }} class Memento {Private String state = "";PublicMemento (String state) {This.state = State; }Public StringGetState () {return state; }PublicvoidSetState (String state) {This.state = State; }} class Caretaker {Private Memento Memento;Public MementoGetmemento () {return memento; }PublicvoidSetmemento (Memento Memento) {this.memento = Memento;} } public class Client {public Span class= "Hljs-keyword" >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 demonstrates an example of single-state single-backup, which is very simple: the state variable in the originator class needs to be backed up so that it can be restored when needed; in the memento class, there is also a status variable that stores the temporary states of the originator class. Whereas the caretaker class is used to manage memo classes to write state to or retrieve state from a 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 StringGetState1 () {return state1; }PublicvoidSetState1 (String state1) {This.state1 = state1; }Public StringGetState2 () {return state2; }PublicvoidSetState2 (String state2) {This.state2 = State2; }Public StringGetState3 () {return state3; }PublicvoidSetState3 (String state3) {This.state3 = State3; }Public MementoCreatememento () {ReturnNew Memento (Beanutils.backupprop (This)); }PublicvoidRestorememento (Memento Memento) {Beanutils.restoreprop (This, Memento.getstatemap ()); }Public StringToString () {Return "state1=" +state1+ "state2=" +state2+ "state3=" +STATE3; }} class Memento {Private map<string, object> Statemap;PublicMemento (map<string, object> Map) {This.statemap = map; }Public map<string, object>Getstatemap () {return statemap; }PublicvoidSetstatemap (map<string, object> statemap) {This.statemap = Statemap; }} class Beanutils {PublicStatic map<string, object>Backupprop (Object Bean) {map<string, object> 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; }PublicStaticvoidRestoreprop (Object Bean, map<string, object> PropMap) {try {BeanInfo 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 MementoGetmemento (String index) {Return Memmap.Get (index); }Publicvoidsetmemento (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 ("= = = Restore Status ===\n" +ori);} }

The advantages of the memo pattern are:

1, 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 saved outside the initiator role, so that the initiator role does not need to manage the status of each backup.

Cons of Memo mode:

1, 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.

23 Design Modes (15): Memo 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.