1类图
2定义:
2.1 在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
3应用场景:
3.1 需要保存一个对象在某一时刻的状态或部分状态。
3.2 如果用一个接口来让其他对象得到这些状态,将会暴露对象的实现细节并破坏对象的封装性,一个对象不希望外界直接访问其内部状态,通过中间对象可以间接访问其内部状态。
4模拟类
public class CallofDuty {
private int mCheckpoint = 1 ;
private int mLifeValue = 100 ;
private String mWeepon = "沙漠之鹰" ;
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 Memoto createMemoto (){
Memoto memoto = new Memoto();
memoto.mCheckpoint = mCheckpoint;
memoto.mLifeValue = mLifeValue;
memoto.mWeapon = mWeepon;
return memoto;
}
public void restore (Memoto memoto){
this .mCheckpoint = memoto.mCheckpoint;
this .mLifeValue = memoto.mLifeValue;
this .mWeepon = memoto.mWeapon;
System.out .println("恢复后的游戏属性 : " + this .toString());
}
@Override
public String toString () {
return "CallofDuty [mCheckpoint=" + mCheckpoint + ", mLifeValue=" + mLifeValue + ", mWeepon=" + mWeepon + "]" ;
}
}
5创建要保存的对象类
public class Memoto {
public int mCheckpoint;
public int mLifeValue;
public String mWeapon;
@Override
public String toString () {
return "Memoto [mCheckpoint=" + mCheckpoint + ", mLifeValue=" + mLifeValue + ", mWeapon=" + mWeapon + "]" ;
}
}
6保存和回复类
public class Caretaker {
Memoto memoto;
public void archive (Memoto memoto){
this .memoto = memoto;
}
public Memoto getMemoto () {
return memoto;
}
}
7测试
public class Client {
public static void main (String[] args) {
CallofDuty game = new CallofDuty();
game.play();
Caretaker caretaker = new Caretaker();
caretaker.archive(game.createMemoto());
game.quit();
CallofDuty newGame = new CallofDuty();
newGame.restore(caretaker.getMemoto());
}
}