备忘录模式又叫做快照模式(Snapshot Pattern)或Token模式,属于行为模式。它是在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态。它包含以下几类角色:
1、Memento:备忘数据的bean;
2、Originator:发起者,需要备份数据的对象,其备份内容与Memento相同,负责创建一份备份数据,并能够通过备份数据回写状态;
3、Caretaker:保存该备份数据的独享,类似第三方存储;
代码如下:
- Memento
public class Memento { private int state; public Memento(int state){ this.state = state; } public int getState() { return state; } public void setState(int state) { this.state = state; } }
- Originator
public class Originator { private int state; public Originator(){ this.state = 0; } public Memento createMemento(){ return new Memento(this.state); } public void setMemento(final Memento memento){ this.state = memento.getState(); } public int getState() { return state; } public void setState(int state) { this.state = state; } }
- Caretaker
public class Caretaker { private Memento memento; public Memento getMemento() { return memento; } public void setMemento(final Memento memento) { this.memento = memento; } }
- APP 测试类
public class App { public static void main(String[] args) { Originator ori = new Originator(); Caretaker cv = new Caretaker(); ori.setState(1); //将状态保存在Caretaker中 cv.setMemento(ori.createMemento()); System.out.println(ori.getState()); ori.setState(2); //将Caretaker中的状态回写 cv.setMemento(cv.getMemento()); System.out.println(ori.getState()); } }
时间: 2024-10-09 13:58:14