备忘录模式适用于功能比较复杂的,但需要维护或者记录属性的类,对象可以根据备忘录回滚到上一状态。
所谓备忘录模式就是在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。
客户不与备忘录类耦合,与备忘录管理类耦合。
uml:
代码:
public class Memento { private String state = null; public Memento(String state) { this.state = state; } public String getState() { return state; } }
public class Caretaker { private Memento memento = null; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
public class Organizer { private String state = null; public String getState() { return state; } public void setState(String state) { this.state = state; } public Memento createMemento() { return new Memento(state); } public void loadMemento(Memento memento) { state = memento.getState(); } public void show() { System.out.println("State: " + state); } }
public class MementoDemo { public static void main(String[] args) { Organizer organizer = new Organizer(); organizer.setState("On"); organizer.show(); Caretaker caretaker = new Caretaker(); caretaker.setMemento(organizer.createMemento()); organizer.setState("Off"); organizer.show(); organizer.loadMemento(caretaker.getMemento()); organizer.show(); } }