首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

备忘录形式

2012-07-02 
备忘录模式3)实例程序//备忘发起(Originator)角色,创建备忘录和恢复备忘录class WindowsSystem{private St

备忘录模式
3)实例程序
//备忘发起(Originator)角色,创建备忘录和恢复备忘录
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;
    }
}
//备忘录角色,存储系统的内部状态
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;
    }
}
//备忘录管理者(Caretaker)角色,负责保存好备忘录。不能对备忘录的内容进行操作或检查。
class User
{
    private Memento memento;

    public Memento retrieveMemento()
    {// 恢复系统
        return this.memento;
    }

    public void saveMemento(Memento memento)
    {// 保存系统
        this.memento = memento;
    }
}
//调用备忘录
public class MementoTest
{
    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());
    }
}
程序执行结果为:
当前系统处于好的状态
可见,系统恢复了备份之前的状态。

热点排行