1. 定义
在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态。
2. 使用场景
- 需要保存/恢复数据的相关状态场景
- 需要提供一个可回滚的操作
3. 优缺点
- 优点:
- 提供可以恢复状态的机制
- 实现了信息的封装,不用关心保存状态的细节
- 缺点:
- 消耗资源(如果类的成员变量过多,每次保存都会消耗一定的内存)
4. Android源码中的使用:
Activity的onSaveInstanceState(),onRestoreInstanceState()两个方法,非主动退出或跳转到其他activity时触发onSaveInstanceState备份数据,下次启动activity时读取备份
5. 实例演示
下面以游戏存档为例
- 首先创建一个游戏类,这里以使命召唤为例
//使命召唤游戏
class CallOfDuty {
private int mCurrentLevel = 1;//当前等级/关卡
private int mLifeBar = 100;//血量
private String mGun = "汉阳造";//武器
//玩
public void play() {
LjyLogUtil.i("使命召唤:");
mLifeBar -= 10;
mCurrentLevel++;
mGun = "沙漠之鹰+Ak47";
LjyLogUtil.i("晋级到第" + mCurrentLevel + "关,当前血量:" + mLifeBar + ",当前武器:" + mGun);
}
//退出
public void quit() {
LjyLogUtil.i("-----quit-------");
LjyLogUtil.i("退出前的游戏属性:\n" + this.toString());
LjyLogUtil.i("-----已退出------");
}
//创建备忘录
public Memoto createMemoto() {
Memoto memoto = new Memoto();
memoto.mCurrentLevel = mCurrentLevel;
memoto.mLifeBar = mLifeBar;
memoto.mGun = mGun;
return memoto;
}
//恢复游戏
public void restore(Memoto memoto) {
this.mCurrentLevel = memoto.mCurrentLevel;
this.mLifeBar = memoto.mLifeBar;
this.mGun = memoto.mGun;
}
@Override
public String toString() {
return "CallOfDuty{" +
"mCurrentLevel=" + mCurrentLevel +
", mLifeBar=" + mLifeBar +
", mGun='" + mGun + '\'' +
'}';
}
}
- 创建一个备份存储类
class Memoto {
private int mCurrentLevel;
private int mLifeBar;
private String mGun;
@Override
public String toString() {
return "Memoto{" +
"mCurrentLevel=" + mCurrentLevel +
", mLifeBar=" + mLifeBar +
", mGun='" + mGun + '\'' +
'}';
}
}
- 创建一个备份管理者类
class Caretaker {
Memoto mMemoto;
//存档
public void saveMemoto(Memoto memoto) {
this.mMemoto = memoto;
}
//读档
public Memoto getMemoto() {
return mMemoto;
}
}
- 最后创建实例进行调用
private void methodMemoPattern() {
//以游戏存档为例,屏蔽了外界对CallOfDuty对象的直接访问
//1.创建
CallOfDuty game = new CallOfDuty();
//2.玩
game.play();
//3.存档
Caretaker caretaker = new Caretaker();
caretaker.saveMemoto(game.createMemoto());
//4.退出
game.quit();
//5.恢复游戏
CallOfDuty newGame = new CallOfDuty();
LjyLogUtil.i("newGame,恢复存档前属性:\n" + newGame.toString());
newGame.restore(caretaker.getMemoto());
LjyLogUtil.i("newGame,恢复存档后游戏属性:\n" + newGame.toString());
}
网友评论