概念:
备忘录模式又叫做快照模式(Snapshot Pattern)或Token模式,属于行为模式。它是在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样适当的时候就可将该对象恢复到原先保存的状态。
思路:
原始类A,A中有各种属性,A可以决定需要备份的属性,备忘录类B是用来存储A的一些内部状态,存储类C,就是一个用来存储备忘录的,且只能存储,不能修改等操作。
类图如下:
案例:
某游戏提供角色状态快照存储功能,当玩家不满意当前游戏进度,可以恢复到快照时候的状态。
技术实现:
快照类:快照可记录游戏角色等级、金币状态
public class Memento {
private int level;
private long gold;
public Memento(int level, long gold) {
this.level = level;
this.gold = gold;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public long getGold() {
return gold;
}
public void setGold(long gold) {
this.gold = gold;
}
}
角色类:内部各种状态,重要的是提供两个方法,快照和恢复快照方法。
public class Player {
private String Name;
private String UID;
private int level = 1;
private long gold = 0;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getUID() {
return UID;
}
public void setUID(String UID) {
this.UID = UID;
}
public Player(String name, String UID) {
Name = name;
this.UID = UID;
}
public int getLevel() {
return level;
}
public Player setLevel(int level) {
this.level = level;
return this;
}
public long getGold() {
return gold;
}
public Player setGold(long gold) {
this.gold = gold;
return this;
}
public Memento getMemento() {
return new Memento(level, gold);
}
public Player restoreMemento(Memento memento) {
System.out.println("player restoreMemento()");
setLevel(memento.getLevel());
setGold(memento.getGold());
return this;
}
}
存储类:
public class WebStorage {
private Memento memento;
public WebStorage(Memento memento) {
this.memento = memento;
}
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
测试类代码:
public class WorkClass {
public void test() {
Player player = new Player("愤怒的小鸟", "uid1001");
player.setLevel(5).setGold(10000);
System.out.println(String.format("Player Information: name:%s,uid:%s,level:%s,gold:%s",
player.getName(),
player.getUID(),
player.getLevel(),
player.getGold()));
WebStorage webStorage = new WebStorage(player.getMemento());
player.setLevel(10).setGold(500);
System.out.println(String.format("Player Information: name:%s,uid:%s,level:%s,gold:%s",
player.getName(),
player.getUID(),
player.getLevel(),
player.getGold()));
//player want to restore
player.restoreMemento(webStorage.getMemento());
System.out.println(String.format("Player Information: name:%s,uid:%s,level:%s,gold:%s",
player.getName(),
player.getUID(),
player.getLevel(),
player.getGold()));
}
}
测试结果输出:
Player Information: name:愤怒的小鸟,uid:uid1001,level:5,gold:10000
Player Information: name:愤怒的小鸟,uid:uid1001,level:10,gold:500
player restoreMemento()
Player Information: name:愤怒的小鸟,uid:uid1001,level:5,gold:10000