标签:blog http ar java 2014 c on log 代码
定义:在不破坏封装性的前提下中,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
结构图:
示例代码:
public class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } } public class Originator { private String state; public String getState() { return state; } public void setState(String state) { this.state = state; } public void setState(Memento memento) { this.state = memento.getState(); } public Memento createMemento() { return new Memento(state); } public void show() { System.out.println("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 o = new Originator(); o.setState("on"); o.show(); Caretaker c = new Caretaker(); c.setMemento(o.createMemento()); o.setState("off"); o.show(); o.setState(c.getMemento()); o.show(); } }运行结果如下:
State=on
State=off
State=on
标签:blog http ar java 2014 c on log 代码
原文地址:http://blog.csdn.net/tiandesheng111/article/details/39802733