Java Design Pattern modeling and implementation of cainiao series (19th) Memorandum Pattern
Memento: stores a state of an object to restore the object as appropriate.
I. uml modeling:
Ii. Code Implementation
/*** Memento: The main purpose is to save a certain state of an object to restore the object when appropriate. ** example: original class --> Create and restore memos */class Original {private String state; public Original (String state) {this. state = state;} public String getState () {return state;} public void setState (String state) {this. state = state;}/*** create memo */public Memento createMemento () {return new Memento (state );} /*** recovery memorandum */public void recoverMemento (Memento memento) {this. state = memento. getState () ;}/ *** memo */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;}/*** used to store a memorandum (holding a memorandum instance): it can only be stored and cannot be modified */class Storage {private Memento memento; public Storage (Memento memento) {this. memento = memento;} public Memento getMemento () {return memento ;}} /*** client Test class ** @ author Leo */public class Test {public static void main (String [] args) {/*** create Original object */original Original = new Original (daytime mode); System. out. println (original initial state: + original. getState ();/*** create memo ** Note: original. createMemento () will pass the initial state (daytime mode) to the Memento object ** in case storage can be called as needed. getMemento () to get the state (daytime mode) ** equivalent to the state (daytime Mode) this state has been delegated to the storage object to save */Storage storage = new Storage (original. createMemento (); original. setState (night mode); System. out. println (original: + original. getState ();/*** recovery memorandum */original. recoverMemento (storage. getMemento (); System. out. println (after original is restored, the status is + original. getState ());}}
Iii. Summary
The Memento memorandum design mode is used to back up the current state of an object. When necessary, use this backup to restore the state of this object at a certain time point.