版权声明: https://blog.csdn.net/if_i_were_a/article/details/84025051
备忘录模式(Memento):在不破坏封装的前提下,捕获一个对象的内部状态,并在改对象之外保存这个状态,这样以后就可以将该对象恢复到之前保存的状态
备忘录模式的类图:
http://img4.imgtn.bdimg.com/it/u=135957181,4212772279&fm=26&gp=0.jpg
备忘录模式的代码:
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 setMemento(Memento memento)
{
state=memento.state;
}
public void show()
{
System.out.println("State="+state);
}
}
public class Memento {
protected String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
public class Caretaker {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
public class Main {
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();
}
}
对于Caretaker类,是用来管理Memento对象的,当有一个Mento对象时,不能明显地看出来这个类的作用,有很多个Menmento对象的时候,CareTaker对象里面存放的是Memento类型的List,里面有get和set方法。
备忘录模式的缺点:
一个类的状态需要完整地存储到备忘录对象中,如果状态数据很大很多,那么在资源消耗上,备忘录对象会非常耗费内存