备忘录(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
package designMode.memento; class Originator { private String state; public Memento createMemento(){ return new Memento(state); } public void setMemento(Memento memento){ state = memento.getState(); } public void show(){ System.out.println("State=:"+state); } public String getState() { return state; } public void setState(String state) { this.state = state; } }
package designMode.memento; class Memento { private String state; public String getState() { return state; } public void setState(String state) { this.state = state; } public Memento(String state){ this.state = state; } }
package designMode.memento; class Caretaker { private Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
package designMode.memento; class Test { public static void main(String[] args) { Originator o = new Originator(); o.setState("on"); o.show(); Caretaker c = new Caretaker(); c.setMemento(o.createMemento()); o.setState("off"); o.show(); o.setMemento(c.getMemento()); o.show(); } }