备忘录(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。[DP]
//首先,我们定义Originator类,它有一个状态和一个方法来创建和恢复备忘录:
public class Originator {private String state;public void setState(String state) {this.state = state;}public String getState() {return state;}// 创建备忘录public Memento createMemento() {return new Memento(this.state);}// 恢复备忘录状态public void restoreMemento(Memento memento) {this.state = memento.getState();}
}
//接下来,我们定义Memento类,它负责存储Originator的状态:
public class Memento {private String state;// 构造器,用于从Originator获取状态信息public Memento(String state) {this.state = state;}// 获取备忘录中的状态信息public String getState() {return state;}
}
//然后,我们定义Caretaker类,它负责管理Memento对象:
public class Caretaker {private Memento memento;// 保存备忘录public void setMemento(Memento memento) {this.memento = memento;}// 获取备忘录public Memento getMemento() {return memento;}
}
//最后,我们编写一个简单的客户端代码来演示如何使用这些类:
public class MementoPatternDemo {public static void main(String[] args) {// 创建Originator对象Originator originator = new Originator();// 创建Caretaker对象Caretaker caretaker = new Caretaker();// 设置Originator的初始状态originator.setState("State A");System.out.println("Originator state: " + originator.getState());// 创建备忘录并保存caretaker.setMemento(originator.createMemento());// 改变Originator的状态originator.setState("State B");System.out.println("Originator state: " + originator.getState());// 从Caretaker恢复备忘录originator.restoreMemento(caretaker.getMemento());System.out.println("Originator state after restoring memento: " + originator.getState());}
}