一、模式定义
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态。
二、模式结构
Originator类:被备份的类,负责生成备份和还原备份
Memento类:用来存储Originator中要备份的属性
CareTaker类:负责存储Memento备份
三、模式实现
public class Originator {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Originator(String value) {
this.value = value;
}
public Memento createMemento(){
return new Memento(value);
}
public void restoreMemento(Memento memento){
this.value = memento.getValue();
}
}
public class Memento {
private String value;
public Memento(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class CareTaker {
private Memento memento;
public CareTaker(Memento memento) {
this.memento = memento;
}
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
public class Test {
public static void main(String[] args) {
// 创建原始类
Originator origi = new Originator("egg");
// 创建备忘录
CareTaker storage = new CareTaker(origi.createMemento());
// 修改原始类的状态
System.out.println("初始化状态为:" + origi.getValue());
origi.setValue("niu");
System.out.println("修改后的状态为:" + origi.getValue());
// 回复原始类的状态
origi.restoreMemento(storage.getMemento());
System.out.println("恢复后的状态为:" + origi.getValue());
}
}
四、使用场景
1.需要保存和恢复数据的相关状态场景。
2.提供一个可回滚的操作,比如说各种编辑器中的Ctrl+Z组合键。
3.需要监控的副本场景中。
4.数据库连接的事务管理就是用的备忘录模式。