Chinaunix首页 | 论坛 | 博客
  • 博客访问: 534603
  • 博文数量: 855
  • 博客积分: 40000
  • 博客等级: 大将
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-16 19:08
文章分类

全部博文(855)

文章存档

2011年(1)

2008年(854)

我的朋友

分类:

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

【责编:landy】

--------------------next---------------------

阅读(328) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~