备忘录模式
class Originator{
private int stateA = 0;
private int stateB = 0;
private int stateC = 0;
public Memoto createMemoto(){
Memoto memoto = new Memoto();
memoto.setStateA(stateA);
memoto.setStateB(stateB);
memoto.setStateC(stateC);
}
public void restore(Memoto memoto){
this.stateA = memoto.getStateA();
this.stateB = memoto.getStateB();
this.stateC = memoto.getStateC();
}
public void change(){
stateA = 1;
stateB = 2;
stateC = 3;
}
public void showData(){
System.out.println(stateA+"=="+stateB+"=="+stateC);
}
}
原始类
class Memoto{
private int stateA;
private int stateB;
private int stateC;
public int getStateA(){
return this.stateA;
}
public int getStateB(){
return this.stateB;
}
public int getStateC(){
return this.stateC;
}
public void setStateA(int a){
this.stateA = a;
}
public void setStateB(int b){
this.stateB = b;
}
public void setStateC(int c){
this.stateC = c;
}
}
数据bean类
class Caretaker{
Memoto memoto;
public Memoto restoreMemoto(){
return this.memoto;//恢复数据
}
public void storeMemoto(Memoto memoto){
this.memoto = memoto;
}
}
备忘录对象,管理Memoto对象
class Cliten{
public static void main(String args[]){
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
originator.showData();//原始数据为 0 0 0
originator.change();//改变之后为 1 2 3
caretaker.storeMemoto(originator.createMemoto());//存储状态
//模拟下次登录之后 重新开始
Originator originatorNew = new Originator();
originatorNew.restore(caretaker.restoreMemoto());
originatorNew.showData();//数据为 1 2 3
}
}
客户端模拟备忘录模式。当需要保存状态的时候将状态存入Caretaker即可。Caretaker这里只是保存最后一次变化状态,可以扩展需求做的更丰富一些。
个人总结
例子比较简单,仅仅只是备忘录模式的原型。一句话概括就是备忘录类会记住应该记住的状态,而存储与恢复状态在原始类中调用。
备忘录模式在Android源码里面例子,当界面退居后台或者由于内存不足被干翻,在这之前会调用Activity中onSaveInstanceState方法保存状态。当界面再次出现在界面上时在onRestoreInstanceState方法中获取之前保存的状态。