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

备忘录模式

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

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

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

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

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

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

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());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值