Java设计模式-----Memento备忘录模式

来源:互联网 发布:网络改写的小说 编辑:程序博客网 时间:2024/05/18 01:05

 源自:http://www.blogjava.net/flustar/archive/2007/12/08/memento.html

Memento备忘录模式:

在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存前的状态。

例子:

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 WindowsSystem {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) {WindowsSystem 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());}}