备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象
备忘录模式的结构
- 发起人:记录当前时刻的内部状态,负责定义哪些属于备份范围的状态,负责创建和恢复备忘录数据。
- 备忘录:负责存储发起人对象的内部状态,在需要的时候提供发起人需要的内部状态。
- 管理角色:对备忘录进行管理,保存和提供备忘录。
Original
package design.pattern.menento; public class Original { private State state; private Menento menento; public Original(Storage sto) { state = new State(); menento = new Menento(sto); } public String getState() { return state.getInfo(); } public void setState(String msg) { state.setInfo(msg); } public void load() { menento.load(); } public void store() { menento.store(); } private class Menento { private Storage storage; private Menento(Storage storage) { this.storage = storage; } private void load() { state = storage.load(); } private void store() { storage.store((State)state.clone()); } } }
State
package design.pattern.menento; public class State implements Cloneable{ private String info; { info = "init"; } public void setInfo(String msg) { info += " -> " + msg; } public String getInfo() { return info; } @Override public Object clone() { State obj; try { obj = (State) super.clone(); obj.info = new String(info); return obj; } catch (CloneNotSupportedException e) { e.printStackTrace(); throw new RuntimeException(); } } }
Storage
package design.pattern.menento; import java.util.ArrayList; import java.util.List; public class Storage { private List<State> list = new ArrayList<>(); public State load() { if (list.isEmpty()) throw new RuntimeException(); return list.remove(0); } public void store(State state) { list.add(state); } }
Client
package design.pattern.menento; public class Client { public static void main(String[] args) { Original ori = new Original(new Storage()); System.out.println(ori.getState()); ori.store(); ori.setState("change"); System.out.println(ori.getState()); ori.load(); System.out.println(ori.getState()); } }