备忘录模式
备忘录(Memento)模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便以后当需要时能将该对象恢复到原先保存的状态。该模式又叫快照模式。
案例
每次玩游戏时从服务器读取存档,退出后保存存档
存档类:
java
public class GameRecoder {
Integer id;
Integer level;
public GameRecoder(Integer id, Integer level) {
this.id = id;
this.level = level;
}
@Override
public String toString() {
return "GameRecoder{" +
"id=" + id +
", level=" + level +
'}';
}
}
服务器:
java
public class GameServer {
Map<Integer,GameRecoder> map = new HashMap<>();
int cur = 0;
{
cur++;
GameRecoder gameRecoder = new GameRecoder(cur, 1);
map.put(cur,gameRecoder);
}
public void addRecord(Integer level){
cur++;
GameRecoder gameRecoder = new GameRecoder(cur, level);
map.put(cur,gameRecoder);
System.out.println("添加存档:"+gameRecoder);
}
public GameRecoder getRecord(){
System.out.println("读取存档:"+map.get(cur));
return map.get(cur);
}
}
游戏:
java
public class MyGame {
private Integer level;
GameServer server = new GameServer();
public void play(){
GameRecoder record = server.getRecord();
level = record.level;
System.out.println("开始游戏,当前等级:"+level);
level++;
}
// 存档
private void save(){
server.addRecord(level);
}
public void exit(){
System.out.println("退出游戏");
save();
}
}
测试:
java
public class Main {
public static void main(String[] args) {
MyGame myGame = new MyGame();
myGame.play();
myGame.exit();
myGame.play();
}
}