随笔分类
备忘录模式
Memento
行为型之一
保存对象的内部状态,并在需要的时候(undo / rollback)恢复对象以前的状态
-
Originator 原生者
需要被保存状态以便被恢复的那个对象
-
Memento 备忘录
该对象由Originator创建,主要用来保存Originator的内部状态
-
Caretaker 管理者
负责在适当的时间保存/恢复Originator对象的状态
public class Person {
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setAge(int age) {
this.age = age;
}
String name;
String sex;
int age;
public Person(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
//创建一个备份
public Memento createMemento(){
return new Memento(this.name, this.sex, this.age);
}
//恢复备份
public void setMemento(Memento memento){
this.name = memento.getName();
this.sex = memento.getSex();
this.age = memento.getAge();
}
}
/**
* 可以看作是简化了的Person,仅用来保存状态和恢复状态
*/
public class Memento {
String name;
String sex;
int age;
public Memento(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public int getAge() {
return age;
}
}
/**
* 用来管理Memento
*/
public class Caretaker {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
/**
* 备忘录模式
* Person{name='liangye', sex='男', age=18}
* Person{name='良夜', sex='男', age=20}
* Person{name='liangye', sex='男', age=18}
*/
public class Client {
public static void main(String[] args) {
Person person = new Person("liangye", "男", 18);
Caretaker caretaker = new Caretaker();
caretaker.setMemento(person.createMemento());
System.out.println(person);
person.setAge(20);
person.setName("良夜");
System.out.println(person);
//rollback
person.setMemento(caretaker.getMemento());
System.out.println(person);
}
}
应用场景
备忘录模式其实在生活中真的是无处不在
- 如果一个对象需要保存状态并可通过undo / rollback等操作恢复到以前的状态,可以使用Memento模式
- 一个类需要保存它的对象状态(相当于Originator角色)
- 设计一个类,用来保存上述对象的状态(相当于Memento角色)
- 需要的时候,Caretaker角色要求Originator放回一个Memento并加以保存
- undo或rollback操作时,通过Caretaker保存的Memento来恢复Originator对象的状态