备忘录模式,其实就是备份模式,先保存原来的状态,再把状态恢复
//发起者内部和备忘录拥有State
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(state);
}
/** 将发起者的状态恢复到备忘录的状态 */
public void restore(Memento memento){
this.state = memento.getState();
}
}
public class Memento {
//备忘记录,记录要备份对象
private String state;
public Memento(String state){
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
public class Caretaker {
//管理备忘记录
private Memento mMemento;
public Memento restoreMemento(){
return mMemento;
}
public void storeMemengto(Memento memento){
this.mMemento = memento;
}
}
新建测试类(代码说明看注释)
public class Client {
public static void main(String[] args) {
Originator originator = new Originator();
originator.setState("off");//设置发起对象的私有属性
//发起对象设置过程中间点
Memento memento = originator.createMemento();
//在创建一个过程中间的管理者
Caretaker caretaker = new Caretaker();
caretaker.storeMemengto(memento);//保存状态
originator.setState("hello");//设置发起对象的在动态该改变属性
//取出状态
memento = caretaker.restoreMemento();
originator.restore(memento);
System.err.println(originator);
}
}
网友评论