设计模式(19)---->备忘录模式

备忘录模式

一、模式定义

在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存前的状态。

备忘录模式又叫做快照模式(Snapshot Pattern)或Token模式,属于行为模式。

二、 结构

组成部分:

  1. 发起人(Originator):负责创建一个备忘录Memento,用以记录当前时刻自身的内部状态,并可使用备忘录恢复内部状态。发起人可以根据需要觉得备忘录存储自己的哪些内部状态。
  2. 备忘录(Memento):负责存储发起人对象的内部状态,并可以防止发起人以外的其他对象访问备忘录。备忘录有两个接口:管理者只能看到备忘录的窄接口,他只能将备忘录传递给其他对象。发起人却可以看到备忘录的宽接口,允许它访问返回到先前状态所需要的所有数据。
  3. 管理者(Caretaker):负责备忘录,不能对备忘录的内容进行访问或者操作。

三、例子---游戏进度保存

实例:以保存游戏进度为例,在游戏角色大战Boss前将该角色的状态存储,与Boss作战后角色的各项能力会下降,如果没有通关,则可利用备忘录进行恢复到战前状态。

Memento

public class Memento {
	private int vitality; //生命力
	private int aggressivity; //攻击力
	private int defencivity; //防御力

	public int getVitality() {
		return vitality;
	}

	public void setVitality(int vitality) {
		this.vitality = vitality;
	}

	public int getAggressivity() {
		return aggressivity;
	}

	public void setAggressivity(int aggressivity) {
		this.aggressivity = aggressivity;
	}

	public int getDefencivity() {
		return defencivity;
	}

	public void setDefencivity(int defencivity) {
		this.defencivity = defencivity;
	}
}

发起人可以看到备忘录的宽接口,允许它访问返回到先前状态所需要的所有数据。

public class PlayerOriginator {
	private int vitality; //生命力
	private int aggressivity; //攻击力
	private int defencivity; //防御力

	public PlayerOriginator(int vitality, int aggressivity, int defencivity) {
		this.vitality = vitality;
		this.aggressivity = aggressivity;
		this.defencivity = defencivity;
	}

	public int getVitality() {
		return vitality;
	}

	public void setVitality(int vitality) {
		this.vitality = vitality;
	}

	public int getAggressivity() {
		return aggressivity;
	}

	public void setAggressivity(int aggressivity) {
		this.aggressivity = aggressivity;
	}

	public int getDefencivity() {
		return defencivity;
	}

	public void setDefencivity(int defencivity) {
		this.defencivity = defencivity;
	}

	public Memento createMemento() {
		Memento memento = new Memento();
		memento.setVitality(this.vitality);
		memento.setAggressivity(this.aggressivity);
		memento.setDefencivity(this.defencivity);
		return memento;
	}

	public void setMemento(Memento memento) {
		this.vitality = memento.getVitality();
		this.aggressivity = memento.getAggressivity();
		this.defencivity = memento.getDefencivity();
	}

	public void showState() {
		System.out.print("vitality:" + this.vitality);
		System.out.print("; aggressivity:" + this.aggressivity);
		System.out.println("; defencivity:" + this.defencivity);
	}
}

管理者  只能看到备忘录的窄接口,他只能将备忘录传递给其他对象

public class Caretaker {
	private Memento memento;

	public Memento getMemento() {
		return memento;
	}

	public void setMemento( Memento memento) {
		this.memento = memento;
	}
}

场景类

public class Client {
	public static void main(final String[] args) {
		PlayerOriginator player = new PlayerOriginator(100, 100, 100);
		System.out.print("player's original attributes are ");
		player.showState();

		Caretaker taker = new Caretaker();
		taker.setMemento(player.createMemento());

		player.setVitality(70);
		player.setAggressivity(60);
		player.setDefencivity(20);

		System.out.print("after player fight with Boss, player's attributes are ");
		player.showState();

		//reset player's attribute
		player.setMemento(taker.getMemento());
		System.out.print("after resetting, player's attributes are ");
		player.showState();

	}

}

运行结果

player's original attributes are vitality:100; aggressivity:100; defencivity:100
after player fight with Boss, player's attributes are vitality:70; aggressivity:60; defencivity:20
after resetting, player's attributes are vitality:100; aggressivity:100; defencivity:100

四、 适用场景

  • 在程序运行过程中,某些对象的状态处在转换过程中,可能由于某种原因需要保存此时对象的状态,以便程序运行到某个特定阶段,需要恢复到对象之前处于某个点时的状态。
  • 如果使用一些公有接口让其它对象来得到对象的状态,便会暴露对象的实现细节。
  • 如果有需要提供回滚操作的需求,使用备忘录模式非常适合,比如jdbc的事务操作,文本编辑器的Ctrl+Z恢复等。

五、备忘录模式的优点:

·当发起人角色中的状态改变时,有可能这是个错误的改变,我们使用备忘录模式就可以把这个错误的改变还原。

·备份的状态是保存在发起人角色之外的,这样,发起人角色就不需要对各个备份的状态进行管理。

六、备忘录模式的缺点:

在实际应用中,备忘录模式都是多状态和多备份的,发起人角色的状态需要存储到备忘录对象中,对资源的消耗是比较严重的。

七、多状态多备份备忘录

       通用代码演示的例子中,Originator类只有一个state变量需要备份,而通常情况下,发起人角色通常是一个javaBean,对象中需要备份的变量不止一个,需要备份的状态也不止一个,这就是多状态多备份备忘录。实现备忘录的方法很多,备忘录模式有很多变形和处理方式,像通用代码那样的方式一般不会用到,多数情况下的备忘录模式,是多状态多备份的。其实实现多状态多备份也很简单,最常用的方法是,我们在Memento中增加一个Map容器来存储所有的状态,在Caretaker类中同样使用一个Map容器才存储所有的备份。下面我们给出一个多状态多备份的例子:

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

class Originator {
	private String state1 = "";
	private String state2 = "";
	private String state3 = "";

	public String getState1() {
		return state1;
	}

	public void setState1(String state1) {
		this.state1 = state1;
	}

	public String getState2() {
		return state2;
	}

	public void setState2(String state2) {
		this.state2 = state2;
	}

	public String getState3() {
		return state3;
	}

	public void setState3(String state3) {
		this.state3 = state3;
	}

	public Memento createMemento() {
		return new Memento(BeanUtils.backupProp(this));
	}

	public void restoreMemento(Memento memento) {
		BeanUtils.restoreProp(this, memento.getStateMap());
	}

	public String toString() {
		return "state1=" + state1 + "state2=" + state2 + "state3=" + state3;
	}
}

class Memento {
	private Map<String, Object> stateMap;

	public Memento(Map<String, Object> map) {
		this.stateMap = map;
	}

	public Map<String, Object> getStateMap() {
		return stateMap;
	}

	public void setStateMap(Map<String, Object> stateMap) {
		this.stateMap = stateMap;
	}
}

class BeanUtils {
	public static Map<String, Object> backupProp(Object bean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] descriptors = beanInfo
					.getPropertyDescriptors();
			for (PropertyDescriptor des : descriptors) {
				String fieldName = des.getName();
				Method getter = des.getReadMethod();
				Object fieldValue = getter.invoke(bean, new Object[] {});
				if (!fieldName.equalsIgnoreCase("class")) {
					result.put(fieldName, fieldValue);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static void restoreProp(Object bean, Map<String, Object> propMap) {
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] descriptors = beanInfo
					.getPropertyDescriptors();
			for (PropertyDescriptor des : descriptors) {
				String fieldName = des.getName();
				if (propMap.containsKey(fieldName)) {
					Method setter = des.getWriteMethod();
					setter
							.invoke(bean,
									new Object[] { propMap.get(fieldName) });
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Caretaker {
	private Map<String, Memento> memMap = new HashMap<String, Memento>();

	public Memento getMemento(String index) {
		return memMap.get(index);
	}

	public void setMemento(String index, Memento memento) {
		this.memMap.put(index, memento);
	}
}

 public class Client {
	public static void main(String[] args) {
		Originator ori = new Originator();
		Caretaker caretaker = new Caretaker();
		ori.setState1("中国");
		ori.setState2("强盛");
		ori.setState3("繁荣");
		System.out.println("===初始化状态===\n" + ori);

		caretaker.setMemento("001", ori.createMemento());
		ori.setState1("软件");
		ori.setState2("架构");
		ori.setState3("优秀");
		System.out.println("===修改后状态===\n" + ori);

		ori.restoreMemento(caretaker.getMemento("001"));
		System.out.println("===恢复后状态===\n" + ori);
	}
}

运行结果

===初始化状态===
state1=中国state2=强盛state3=繁荣
===修改后状态===
state1=软件state2=架构state3=优秀
===恢复后状态===
state1=中国state2=强盛state3=繁荣

参考:

http://www.cnblogs.com/itTeacher/archive/2012/12/12/2814814.html

http://www.blogjava.net/flustar/archive/2007/12/08/memento.html

http://blog.csdn.net/zhengzhb/article/details/7697549

 

posted on 2013-06-08 20:59  小强斋太  阅读(191)  评论(0编辑  收藏  举报

导航