设计模式的应用场景(21)--备忘录模式

来源:互联网 发布:进气压力传感器数据值 编辑:程序博客网 时间:2024/04/30 08:28

备忘录模式

定义:该模式就是一个对象复制保存另外一个对象内部状态的对象。便于将对象状态恢复到原先保存的状态。

优点:可以避免暴露一些应由源发器(就是生产原始对象的类)管理却又必须存储在源发器之外的信息。

缺点:开销大代价可能高。要保存的可能信息多,或者频繁保存恢复。

使用时机:当系统必须要保存一个对象在某一个时刻的状态,以方便需要的时候能恢复到先前的状态时,就可以使用备忘录模式。

领导找小巩建立一个会议纪要系统,需要保存相关信息,需要的时候可以查阅。

首先设计一个会议纪要类,记录会议名字,参与人名,内容,用于被保存或被恢复的对象。

public class Cahier {    private String name;    private String content;    private String persons;    public void setName (String name) {        this.name =  name;    }    public String getName () {        return this.name;    }    public void setContent (String content) {        this.content = content;    }    public String getContent () {        return this.content;    }    public void setPersons (String persons) {        this.persons =  persons;    }    public String getPersons () {        return this.persons;    }    public Memento getMemento() {        return new Memento(this);    }    public void setMemento(Memento memento) {        this.name = memento.getName();        this.content = memento.getContent ();        this.persons = memento.getPersons ();    }}

下面分别实现源发器和备忘录

public class Originator {    public Memento getMemento(){ return memento; }    public void setMemento(Memento memento){ this.memento = memento; }    private Memento memento;}public class Memento {    private String name;    private String content;    private String persons;    public Memento (Cahier cahier) {        this.name = cahier.getName();        this.content = cahier.getContent ();        this.persons = cahier.getPersons ();    }    public void setName (String name) {        this.name =  name;    }    public String getName () {        return this.name;    }    public void setContent (String content) {        this.content = content;    }    public String getContent () {        return this.content;    }    public void setPersons (String persons) {        this.persons =  persons;    }    public String getPersons () {        return this.persons;    }}

下面显示客服端调用代码,可以看到有恢复undo功能

public class Client {    public static void main(String[] argv) {        Cahier cahier = new Cahier();        cahier.setName("公司销售会议");        cahier.setContent("有关销售价格的会议内容");        cahier.setPersons("总经理、销售处长");        System.out.println("原来的内容" + cahier.getName() + " :" + cahier.getContent() +  " :" + cahier.getPersons());        Memento memento = cahier.getMemento();        //进行其它代码的处理        cahier.setName("公司办公会议");        cahier.setContent("有关员工稳定的会议内容");        cahier.setPersons("董事长、总经理、人事副总");        System.out.println("修改后的内容" + cahier.getName() + " :" + cahier.getContent() +  " :" + cahier.getPersons());        //恢复原来的代码        cahier.setMemento(memento);        System.out.println("恢复到原来的内容" + cahier.getName() + " :" + cahier.getContent() +  " :" + cahier.getPersons());    }}