定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
使用场景:需要恢复状态场景,提供一个回滚的操作
实现:创建备忘录类,封装要保存的数据。发起者增加保存状态的方法,返回封装了当前对象数据的备忘录类对象,并提供恢复状态的方法,创建状态管理者类,保存备忘录类对象以便需要恢复时提供数据
优点:提供可恢复的操作,并且不破坏封装性。
缺点:耗内存

代码示例:游戏进度保存
/**
* 游戏角色类
* @author liuhao
*
*/
public class Role {
private int lifeValue;
private int attackValue;
public RoleMemento saveState() {
return new RoleMemento(lifeValue, attackValue);
}
public void restoreState(RoleMemento roleMemento) {
this.attackValue = roleMemento.getAttackValue();
this.lifeValue = roleMemento.getLifeValue();
}
public String show() {
return "Role [lifeValue=" + lifeValue + ", attackValue=" + attackValue + "]";
}
public int getLifeValue() {
return lifeValue;
}
public void setLifeValue(int lifeValue) {
this.lifeValue = lifeValue;
}
public int getAttackValue() {
return attackValue;
}
public void setAttackValue(int attackValue) {
this.attackValue = attackValue;
}
}
/**
* 备忘录类
* @author liuhao
*
*/
public class RoleMemento {
private int lifeValue;
private int attackValue;
public RoleMemento(int lifeValue, int attackValue) {
this.lifeValue = lifeValue;
this.attackValue = attackValue;
}
public int getLifeValue() {
return lifeValue;
}
public void setLifeValue(int lifeValue) {
this.lifeValue = lifeValue;
}
public int getAttackValue() {
return attackValue;
}
public void setAttackValue(int attackValue) {
this.attackValue = attackValue;
}
}
/**
* 管理者类
* @author liuhao
*
*/
public class Caretaker {
private RoleMemento memento;
public RoleMemento getMemento() {
return memento;
}
public void setMemento(RoleMemento memento) {
this.memento = memento;
}
}
public class Main {
public static void main(String[] args) {
Role role = new Role();
role.setLifeValue(100);
role.setAttackValue(100);
System.out.println("初始化状态:");
System.out.println(role.show());
Caretaker caretaker = new Caretaker();
caretaker.setMemento(role.saveState());
role.setLifeValue(0);
role.setAttackValue(0);
System.out.println("死亡状态:");
System.out.println(role.show());
//恢复
role.restoreState(caretaker.getMemento());
System.out.println("恢复后状态:");
System.out.println(role.show());
}
}
结果:
本文详细介绍了备忘录设计模式,一种允许对象在不破坏封装性的前提下保存和恢复其内部状态的方法。通过游戏进度保存的代码示例,展示了如何使用备忘录模式来实现状态的回滚操作。
1856

被折叠的 条评论
为什么被折叠?



