备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先的状态。
举个栗子:打游戏时候需要存档,BOSS打不过之后可以恢复之前的数据继续玩。
游戏角色GameRole
public class GameRole {
/**
* 生命力
*/
private int vitality;
/**
* 攻击力
*/
private int attack;
/**
* 防御力
*/
private int defense;
public void stateDisplay(){
System.out.println("角色目前状态:");
System.out.println("生命力:" + vitality);
System.out.println("攻击力:" + attack);
System.out.println("防御力:" + defense);
}
public void initRoleState(){
this.vitality = 100;
this.attack = 100;
this.defense = 100;
}
public void fight(){
this.vitality = 0;
this.attack = 0;
this.defense = 0;
}
/**
* 保存角色当前状态
* @return
*/
public RoleStateMemento saveState(){
return new RoleStateMemento(vitality, attack, defense);
}
/**
* 恢复角色之前的状态
* @param memento
*/
public void recoveryState(RoleStateMemento memento){
this.vitality = memento.vitality;
this.attack = memento.attack;
this.defense = memento.defense;
}
}
角色状态储存类(备忘录)RoleStateMemento
/**
* 角色状态备忘录,保存角色状态
*/
public class RoleStateMemento {
public int vitality;
public int attack;
public int defense;
public RoleStateMemento(int vitality, int attack, int defense) {
this.vitality = vitality;
this.attack = attack;
this.defense = defense;
}
}
角色状态管理者类:
public class RoleStateCaretaker {
private RoleStateMemento memento;
public RoleStateMemento getMemento() {
return memento;
}
public void setMemento(RoleStateMemento memento) {
this.memento = memento;
}
}
客户端代码:
public class MementoTest {
public static void main(String[] args) {
GameRole role = new GameRole();
role.initRoleState();
System.out.println("初始化状态");
role.stateDisplay();
// 保存角色当前状态
RoleStateCaretaker caretaker = new RoleStateCaretaker();
caretaker.setMemento(role.saveState());
role.fight();
System.out.println("经历打斗后");
role.stateDisplay();
// 恢复角色状态
role.recoveryState(caretaker.getMemento());
System.out.println("状态恢复后");
role.stateDisplay();
}
}
输出:
初始化状态
角色目前状态:
生命力:100
攻击力:100
防御力:100
经历打斗后
角色目前状态:
生命力:0
攻击力:0
防御力:0
状态恢复后
角色目前状态:
生命力:100
攻击力:100
防御力:100
上面的例子用备忘录模式保存了游戏进度,把要保存的细节封装到了Memento中,哪一天要更改保存的细节也不用影响客户端了。
备忘录模式应用场景:
Memento模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性的一小部分时,Originator可以根据保存的Memento信息还原到前一状态。使用备忘录模式可以把复杂的对象内部信息对其它的对象屏蔽起来。
其最大的作用还是在当角色的状态改变的时候,有可能这个状态无效,这时候就可以使用暂时存储起来的备忘录将状态复原。