一、意图
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
二、适用性
以下情况使用备忘录模式:
- 必须保存一个对象在某一时刻的(部分)状态,这样以后需要时它才能恢复到先前的状态。
- 如果一个用接口来让其它对象直接取得这些状态,将会暴露对象的实现细节并破坏对象的封装性。
三、结构
四、代码
public class CallOfDuty {
private int mCheckpoint = 1;
private int mLifeValue = 100;
private String mWeapon = "沙漠之鹰";
public void play() {
System.out.println("玩游戏: " + String.format("第%d关", mCheckpoint) + "奋战杀敌中");
mLifeValue -= 10;
System.out.println("进度升级啦");
mCheckpoint++;
System.out.println("到达 " + String.format("第%d关", mCheckpoint));
}
public void quit() {
System.out.println("-----------------");
System.out.println("退出前游戏属性: " + this.toString());
System.out.println("退出游戏");
System.out.println("-----------------");
}
public Memento createMemento() {
Memento memento = new Memento();
memento.mCheckPoint = this.mCheckpoint;
memento.mLifeValue = this.mLifeValue;
memento.mWeapon = this.mWeapon;
return memento;
}
public void restore(Memento memento){
this.mCheckpoint =memento.mCheckPoint;
this.mLifeValue = memento.mLifeValue;
this.mWeapon = memento.mWeapon;
System.out.println("恢复后的游戏属性: "+this.toString());
}
@Override
public String toString() {
return "CallOfDuty{" +
"mCheckpoint=" + mCheckpoint +
", mLifeValue=" + mLifeValue +
", mWeapon='" + mWeapon + '\'' +
'}';
}
}
public class Memento {
public int mCheckPoint;
public int mLifeValue;
public String mWeapon;
@Override
public String toString() {
return "Memento{" +
"mCheckPoint=" + mCheckPoint +
", mLifeValue=" + mLifeValue +
", mWeapon='" + mWeapon + '\'' +
'}';
}
}
public class Caretaker {
Memento memento;
public void archive(Memento memento){
this.memento = memento;
}
public Memento getMemento(){
return memento;
}
}
public class Client {
public static void main(String[] args){
// 构建游戏对象
CallOfDuty game = new CallOfDuty();
game.play();
Caretaker caretaker = new Caretaker();
caretaker.archive(game.createMemento());
game.quit();
CallOfDuty newGame = new CallOfDuty();
newGame.restore(caretaker.memento);
}
}