备忘录模式(Memento)
定义:
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保持这个状态。这样以后就可以将该对象恢复到原先保存的状态。
特点:
示例:
import android.util.Log;
/**
* 原始数据:
*
*/
public class Originator {
//原始数据的某个状态,需要去备份
private String mState;
public String getState() {
return mState;
}
public void setState(String state) {
mState = state;
}
//用于生成需要保存的备份
public Memento createMemento() {
return new Memento(mState);
}
//恢复状态,从备份中读取
public void setMemento(Memento memento) {
mState = memento.getState();
}
public void show() {
Log.d("Originator", "状态:" + mState);
}
}
/**
* 备忘录类:需要保存Originator中需要备份的所有属性
* 此仅以state为例
*/
public class Memento {
//保存源数据中的状态
private String mState;
public String getState() {
return mState;
}
public void setState(String state) {
this.mState = state;
}
public Memento(String state) {
this.mState = state;
}
}
/**
* 保存备忘录的类
*/
public class Caretaker {
private Memento mMemento;
public Memento getMemento() {
return mMemento;
}
public void setMemento(Memento memento) {
this.mMemento = memento;
}
}
/**
* 调用客户端
*/
public class Client {
public void main() {
//初始状态为ON
Originator originator = new Originator();
originator.setState("ON");
originator.show();
//保存此状态,类似进度
Caretaker caretaker = new Caretaker();
caretaker.setMemento(originator.createMemento());
//新状态
originator.setState("OFF");
originator.show();
//恢复上次保存的状态
originator.setMemento(caretaker.getMemento());
originator.show();
}
}