标签:
备忘录(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态。
package Memento; //发起人 public class Originator { //记录此刻内部状态 private String state; public String getState() { return state; } public void setState(String state) { this.state = state; } //创建一个备忘录保存state public Memento createMemento(){ return new Memento(state); } //恢复备忘录保存state public void setMemento(Memento memento){ state=memento.getState(); } public void show() { System.out.println("State="+state); } }
package Memento; //备忘录 public class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } }
package Memento; //管理者 public class Caretaker { //负责保存好备忘录Memento private Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } public static void main(String[] args) { Originator originator=new Originator(); //初始化状态 originator.setState("On"); originator.show(); //保存状态,由于有了很好的封装可以隐藏originator的实现细节 Caretaker caretaker=new Caretaker(); caretaker.setMemento(originator.createMemento()); //改变状态 originator.setState("Off"); originator.show(); originator.setMemento(caretaker.memento); originator.show(); } }
标签:
原文地址:http://www.cnblogs.com/linkarl/p/4852161.html