first, what is the memo mode Memento mode, also known as Memo mode, is one of the behavior patterns that is used to preserve the internal state of the object and restore the previous state of the object when needed (Undo/rollback).
II. Application Scenarios for Memo mode you can use Memento mode if an object needs to save state and can revert to a previous state by using Undo or rollback.
1) A class needs to save the state of its object (equivalent to the originator role)
2) Design a class that is simply used to hold the state of the above object (equivalent to the memento role)
3) when needed, the caretaker role requires originator to return a memento and save
4) Undo or rollback operation restores the state of the originator object through caretaker saved Memento
III. Structure of the memorandum pattern
Iv. roles and responsibilities of the Memorandum model Originator (native person)
The object that needs to be saved in order to be restored.
Memento (Memo)
This object is created by originator and is used primarily to hold the internal state of the originator.
Caretaker (manager)
Responsible for saving/recovering the state of the originator object at the appropriate time.
v. Examples
Person.java
public class Person {private S
Tring name;
Private String sex;
private int age;
Public person () {} public person (string n, string s, int a) {name = N;
sex = s;
age = A;
} public String GetName () {return name;
} public void SetName (String n) {name = N;
} public String Getsex () {return sex;
} public void Setsex (String s) {sex = s;
} public int Getage () {return age;
} public void Setage (int a) {age = A;
} public void Display () {System.out.println ("name:" + name + ", sex:" + sex + ", Age:" + age ");
}//Creage a memento public memento creatememento () {Return to new memento (name, sex, age);
}//Restore public void Setmemento (Memento Memento) {name = Memento.getname ();
Sex = Memento.getsex (); Age = Memento.getage ();
}
}
Memento.java
public class Memento extends person {
private String name;
Private String sex;
private int age;
Public Memento (string n, string s, int a) {
super (n, S, a);
}
}
Caretaker.java
public class Caretaker {
private Memento Memento;
Public Memento Getmemento () {
return Memento;
}
public void Setmemento (Memento m) {
Memento = m;
}
}
Mainclass.java
public class MainClass {public
static void Main (string[] args) {person
p = new Person ("Jim", "Male", +);
Caretaker caretaker = new Caretaker ();
Memento m = P.creatememento ();
Caretaker.setmemento (P.creatememento ());
System.out.println (M.getname ());
P.display ();
P.setname ("John");
P.setage (a);
P.display ();
P.setmemento (Caretaker.getmemento ());
P.display ();
}
}
Output