分类:
2008-10-16 19:19:57
源自:
Memento备忘录模式:
在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存前的状态。
例子:
view plaincopy to clipboardprint?
package memento;
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;
}
}
package memento;
public class System {
private String state;
public Memento createMemento() { // 创建系统备份
return new Memento(state);
}
public void restoreMemento(Memento m) { // 恢复系统
this.state = m.getState();
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
System.out.println("当前系统处于" + this.state);
}
}
package memento;
public class User {
private Memento memento;
public Memento retrieveMemento() { // 恢复系统
return this.memento;
}
public void saveMemento(Memento memento) { // 保存系统
this.memento = memento;
}
}
package memento;
public class Client {
public static void main(String[] args) {
System Winxp = new WindowsSystem(); // Winxp系统
User user = new User(); // 某一用户
Winxp.setState("好的状态"); // Winxp处于好的运行状态
user.saveMemento(Winxp.createMemento()); // 用户对系统进行备份,Winxp系统要产生备份文件
Winxp.setState("坏的状态"); // Winxp处于不好的运行状态
Winxp.restoreMemento(user.retrieveMemento()); // 用户发恢复命令,系统进行恢复
System.out.println("当前系统处于" + Winxp.getState());
}
}