码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-备忘录模式

时间:2014-12-29 09:04:58      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:设计模式   备忘录模式   

意图:在不破坏对象封装性的前提下,在对象的外部得到并保存对象内部的状态,这样对象以后还能恢复到原来的状态。像是备份对象的内部信息。

参与者:

memento(备忘录),存储原发器的内部状态。

Originator(原发器),创建备忘录,纪录自己当前的状态,以及使用备忘录恢复对象的状态。

CareTaker(负责人),负责保存好备忘录,并且保护备忘录不能被改变。

缺点:使用备忘录的代价很高,如果原发器创建备忘录时,必须拷贝并存储大量数据,或者客户端要频繁的创建和恢复原发器的状态,可能会导致很大的开销。

java代码实现如下:

package com.zqwei.memento;

public class Originator {

	private Memento memento;
	
	private String name = null;
	
	public Originator(String name) {
		this.name = name;
	}

	public Memento createMemento() {
		return  new Memento(name);
	}
	public void restoreMemento(Memento memento) {
		this.name = memento.getName();
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
public class Memento {

	private String name;
		
	public Memento(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
		
		
}
	
public class CareTaker {
	private Memento memento;
		
	public CareTaker(Memento memento) {
		this.memento = memento;
	}
		
	public Memento getMemento(){
		return memento;
	}
}



public class Test {

	public static void main(String[] args) {
		Originator ori = new Originator("zhangsan");
		CareTaker careTaker = new CareTaker(ori.createMemento());
		
		System.out.println("before modify, name is "+ori.getName());
		ori.setName("lisi");
		System.out.println("after modify,name is "+ori.getName());
		ori.restoreMemento(careTaker.getMemento());
		System.out.println("after restore, name is"+ori.getName());
	}
}

设计模式-备忘录模式

标签:设计模式   备忘录模式   

原文地址:http://blog.csdn.net/hello0370/article/details/42218493

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!