标签:
定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并咋该对象之外保存这个状态
类图:
代码:
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(this.state); } public void restoreMemento(Memento memento){ setState(memento.getState()); } }
public class Memento { private String state = ""; public Memento(String state){ this.state = state; } public String getState(){ return state; } public void setState(String state){ this.state = 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(); Caretaker caretaker = new Caretaker(); caretaker.setMemento(originator.createMemento()); originator.restoreMemento(caretaker.getMemento()); } }
clone方式的备忘录
类图:
代码:
public class Originator implements Cloneable{ private String state = ""; private Originator backup; public String getState(){ return state; } public void setState(String state){ this.state =state; } public void createMemento(){ backup = this.clone(); } public void restoreMemento(){ this.setState(backup.state); } @Override protected Originator clone(){ try{ return (Originator) super.clone(); }catch(Exception e){ e.printStackTrace(); } return null; } }
多种状态备忘录模式
实现思路:通过反射方式,将各个状态的getter和setter方法以及各个状态保存在map中,而Memento中存储这个map
更好的封装:
目的:防止备份被修改
类图:
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 restoreMemento(IMemento imemento){ setState(((Memento) imemento).getState()); } private class Memento implements IMemento{ private String state = ""; private Memento(String state){ this.state = state; } private String getState(){ return state; } private void setState(String state){ this.state = state; } } }
标签:
原文地址:http://blog.csdn.net/renpengddxx/article/details/52143030