定义(百度百科):
在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
UML类图:
具体代码:
public class Originator { private String state; public Memento createMemento() { return new Memento(this); } public void restoreMemento(Memento m) { state = m.getState(); } public void setState(String state) { this.state=state; } public String getState() { return this.state; } } public class Memento { private String state; public Memento(Originator o) { state = o.getState(); } public void setState(String state) { this.state=state; } public String getState() { return this.state; } } public class Caretaker { private Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento=memento; } } public class Client { public static void main(String[] args) { Originator originator = new Originator(); originator.setState("123"); Memento memento = new Memento(originator); originator.setState("456"); Caretaker caretaker = new Caretaker(); caretaker.setMemento(memento); System.out.println(originator.getState()); originator.restoreMemento(caretaker.getMemento()); System.out.println(originator.getState()); } } 456 123
各模块说明:
Memento:备忘录,存储Originator的对象状态,存储哪些应该由Originator决定。
Originator:原发器,使用备忘录保存某一时刻的状态,也可以使用备忘录恢复某一时刻状态。
Caretaker:备忘录管理者,保存备忘录内容,但不能改变和查看备忘录状态。
适应场景:
保存一个对象在某一个时刻的全部状态或部分状态,实现撤销操作。
防止外界对象破坏一个对象历史状态的封装性,避免将对象历史状态的实现细节暴露给外界对象。
优缺点:
优点:
更好的封装性
简化原发器
缺点:
可能导致高开销(频繁访问和创建备忘录)
总结:
保存和恢复原发器内部状态。