備忘錄模式

備忘錄模式UML.png
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;
}
}
數(shù)據(jù)bean類
class Caretaker{
Memoto memoto;
public Memoto restoreMemoto(){
return this.memoto;//恢復(fù)數(shù)據(jù)
}
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();//原始數(shù)據(jù)為 0 0 0
originator.change();//改變之后為 1 2 3
caretaker.storeMemoto(originator.createMemoto());//存儲狀態(tài)
//模擬下次登錄之后 重新開始
Originator originatorNew = new Originator();
originatorNew.restore(caretaker.restoreMemoto());
originatorNew.showData();//數(shù)據(jù)為 1 2 3
}
}
客戶端模擬備忘錄模式。當(dāng)需要保存狀態(tài)的時候?qū)顟B(tài)存入Caretaker即可。Caretaker這里只是保存最后一次變化狀態(tài),可以擴(kuò)展需求做的更豐富一些。
個人總結(jié)
例子比較簡單,僅僅只是備忘錄模式的原型。一句話概括就是備忘錄類會記住應(yīng)該記住的狀態(tài),而存儲與恢復(fù)狀態(tài)在原始類中調(diào)用。
備忘錄模式在Android源碼里面例子,當(dāng)界面退居后臺或者由于內(nèi)存不足被干翻,在這之前會調(diào)用Activity中onSaveInstanceState方法保存狀態(tài)。當(dāng)界面再次出現(xiàn)在界面上時在onRestoreInstanceState方法中獲取之前保存的狀態(tài)。