概念:在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
备忘录结构
Originator(发起人):负责创建一个备忘录Memento,用以记录当期那时刻它的内存状态,并可使用备忘录恢复内部状态。
Memento(备忘录)负责存储Originator对象的内部状态
Caretaker:负责保存好备忘录Memento
java代码:
public class MementoTest {
public static void main(String[] args) {
Originator originator = new Originator("备忘录模式");
//记录
Caretaker caretaker = new Caretaker(originator.createMemento());
originator.setState("更改内存值");
System.out.println(originator.getState());
//还原
originator.setMemento(caretaker.memento);
System.out.println(originator.getState());
}
//发起人
public class Originator {
private String state;
public Originator(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Memento createMemento(){
return new Memento(state);
}
public void setMemento(Memento memento){
state = memento.state;
}
}
//备忘录
public class Memento {
String state;
public Memento(String state){
this.state = state;
}
}
//保存备忘录
public class Caretaker {
Memento memento;
public Caretaker(Memento memento){
this.memento = memento;
}
}