备忘录模式,又称快照模式或 Token 模式。
备忘录模式的定义 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样,以后就可以将该对象恢复到以前保存的状态
备忘录模式的参与者
发起人角色
public class Originator {
// 内部状态变量
private String state = "";
public String getState() {
return state;
}
// 记录当前时刻的内部状态
public void setState(String state) {
this.state = state;
}
// 创建备忘录角色
public Memento createMemento() {
return new Memento(this.state);
}
// 恢复备份数据
public void restoreMemeto(Memento memento) {
this.setState(memento.getState());
}
}
备忘录角色
public class Memento {
// 发起人的状态
private String state;
public Memento(String state) {
super();
this.state = state;
}
// 提供发起人所需的内部状态
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
}
备忘录管理员
public class Caretaker {
// 备忘录角色
private Memento memento;
// 提供备忘录
public Memento getMemento() {
return memento;
}
// 保存备忘录
public void setMemento(Memento _memento) {
this.memento = _memento;
}
}
备忘录模式的使用场景
备忘录模式的注意事项