说在开头:其实我个人并不认为这是什么设计模式...因为完全没有什么价值嘛,不过既然多本书上对其有介绍,那我还是写一下吧!
备忘录模式是用来实现 备份,还原 的一种代码组织结构; 什么时候需要备份还原呢?非常常见的是游戏中的保存进度, 打BOSS前需要先将当前进度保存一下,等到一不小心挂了,还可以马上恢复到打BOSS前...不然得江湖再见一切重头开始,那该多蛋疼???
那好,我们就以游戏为例写一段代码吧!
//游戏角色
class Role{
//攻击点数
private int attackCount;
//防御点数
private int defenceForcesCount;
//经验数
private int experieceCount;
//精力//该数是不需要存档的...
private int vigorCount;
public int getAttackCount() {
return attackCount;
}
public void setAttackCount(int attackCount) {this.attackCount = attackCount;}
public int getDefenceForcesCount() {return defenceForcesCount;}
public void setDefenceForcesCount(int defenceForcesCount) {this.defenceForcesCount = defenceForcesCount;}
public int getExperieceCount() {return experieceCount;}
public void setExperieceCount(int experieceCount) {this.experieceCount = experieceCount;}
public int getVigorCount() {return vigorCount;}
public void setVigorCount(int vigorCount) {this.vigorCount = vigorCount;}
@Override
public String toString() {
return "Role [attackCount=" + attackCount + ", defenceForcesCount="
+ defenceForcesCount + ", experieceCount=" + experieceCount
+ ", vigorCount=" + vigorCount + "]";
}
}
//备份数据管理者接口,也就是存档位置,
//我们在单机游戏中不是可以看到多个存档点么,我们可以自由选择存档点嘛!
interface Director{
//备份
void preserve(Role role );
//读取存档点还原
Role rollBack();
}
//存档位置1
class DirectorOne implements Director{
private Role role;
@Override
public void preserve(Role role) {
this.role = role;
}
@Override
public Role rollBack() {
return this.role;
}
}
//备份帮助者对象,这里注意一下,其实我们可以直接对Role对象进行克隆,完全复制一份进行保存而不要这个对象,
//之所以一个个属性去get and set,是因为可能有某些值是不需要备份的,比如精力
class BackHelper{
/***
* 进行备份的地方
* @param role 要备份的角色
* @param director 要备份到那个存档点
*/
public void preserve( Role role,Director director){
Role newRole = new Role();
newRole.setAttackCount(role.getAttackCount());
newRole.setDefenceForcesCount(role.getDefenceForcesCount());
newRole.setExperieceCount(role.getExperieceCount());
director.preserve(newRole);
}
}
public class Test {
public static void main(String[] args) {
Role role = new Role();
role.setAttackCount(10);
role.setDefenceForcesCount(88);
role.setExperieceCount(100);
role.setVigorCount(72);
System.out.println(role);
//备份一下,保存到存档点
Director director = new DirectorOne();
BackHelper backHelper = new BackHelper();
backHelper.preserve(role, director);
//戴上了某件超强装备,改变攻击力
role.setAttackCount(10000);
System.out.println(role);
//打BOSS死了,重新读档
role = director.rollBack();
System.out.println(role);
}
}
Role [attackCount=10, defenceForcesCount=88, experieceCount=100, vigorCount=72]
Role [attackCount=10000, defenceForcesCount=88, experieceCount=100, vigorCount=72]
Role [attackCount=10, defenceForcesCount=88, experieceCount=100, vigorCount=0]
***********************************************************************
Ok,就写这么多吧,实在没什么好些的...