Intent: To get and save the state inside the object without destroying the encapsulation of the object, so that the object can revert back to its original state. Like the internal information of the Backup object.
Participants:
Memento (Memo), which stores the internal state of the original generator.
Originator, create a memo, record your current status, and use a memo to restore the state of an object.
Caretaker (person in charge), responsible for keeping the memo, and the protection memo cannot be changed.
Cons: The cost of using a memo is high, and it can be expensive to copy and store large amounts of data when the original is created, or to frequently create and restore the state of the original generator.
The Java code is implemented as follows:
Package Com.zqwei.memento;public class Originator {private Memento memento;private String name = null;public Originator (S Tring name) {this.name = name;} Public Memento Creatememento () {return new Memento (name);} public void Restorememento (Memento Memento) {this.name = Memento.getname ();} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} public class Memento {private string name;public Memento (String name) {this.name = name;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} public class Caretaker {private Memento memento;public caretaker (Memento Memento) {this.memento = Memento;} Public Memento Getmemento () {return Memento;}} public class Test {public static void main (string[] args) {originator Ori = new Originator ("Zhangsan"); Caretaker caretaker = new Caretaker (Ori.creatememento ()); System.out.println ("before modify, name is" +ori.getname ()); Ori.setname ("Lisi"); System.out.println ("After Modify,name is" +ori.getName ()); Ori.restorememento (Caretaker.getmemento ()); SYSTEM.OUT.PRINTLN ("After restore, name is" +ori.getname ());}}
Design mode-Memo mode