备忘录模式
备忘录模式,办公人员几乎每天都会用到,不论我们在编辑什么类型的文档,还是编程,聊天,玩游戏,都在无时不刻的在使用它。
那么,还是举一个简单的栗子,我们都在编辑文档的时候,使用过Ctrl+Z来撤销我们输入的错误内容,那么为什么当我们按下Ctrl+Z的时候,能将文本返回到上一个状态呢,这还是因为有个备忘录在记录每个时刻的状态,当你按下Ctrl+Z的时候,就将某一时刻备份的数据恢复出来。
我们还是来用代码实现一下
原始类Editor是实时文本数据,Memento是备忘录,从来保存某个时刻Editor的数据,还有一个Storage用来存储管理备忘录Memento对象,但是仓库中只能存入和取出,不能修改内容,Memento按照规定,也不能修改内部保存的内容。
Editor类
/**
* @author: hx
* @Time: 2019/5/23
* @Description: Editor
*/
public class Editor {
/**
* 编辑的文本内容
*/
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/**
* 创建一个备忘录
* @return
*/
public Memento createMemento(){
return new Memento(content);
}
/**
* 回复一个备忘录的数据
* @param memento
*/
public void restoreMemento(Memento memento){
content = memento.getContent();
}
}
Memento类
/**
* @author: hx
* @Time: 2019/5/23
* @Description: Memento
*/
public class Memento {
private String content;
public Memento(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
Storage类
/**
* @author: hx
* @Time: 2019/5/23
* @Description: Storage
*/
public class Storage {
/**
* 存储备忘录的集合
*/
private LinkedList<Memento> mMementos;
public Storage() {
mMementos = new LinkedList<>();
}
/**
* 保存一个备忘录
* @param memento
*/
public void addMemento(Memento memento){
mMementos.addFirst(memento);
}
public Memento revert(){
Memento memento = mMementos.getFirst();
mMementos.removeFirst();
return memento;
}
}
然后实际操作一下
public static void main(String[] args){
Storage storage = new Storage();
Editor editor = new Editor();
editor.setContent("123456789");
storage.addMemento(editor.createMemento());
System.out.println("第一次内容:"+editor.getContent());
editor.setContent("132456789qwe");
storage.addMemento(editor.createMemento());
System.out.println("第二次内容:"+editor.getContent());
editor.setContent("132456789qwe!@#$%^");
System.out.println("第三次内容:"+editor.getContent());
//撤销操作
editor.restoreMemento(storage.revert());
System.out.println("第一次撤销:"+editor.getContent());
editor.restoreMemento(storage.revert());
System.out.println("第二次撤销:"+editor.getContent());
}
输出结果:
第一次内容:123456789
第二次内容:132456789qwe
第三次内容:132456789qwe!@#$%^
第一次撤销:132456789qwe
第二次撤销:123456789
这里需要特别注意的是,当保存的对象不是基本数据类型的时候,保存的是数据的引用,所以如果是备份一个对象,需要重新创建一个对象并对对象赋值,或者将要保存的对象实现cloneabe接口。
细心的同学可能已经发现了,这个和原型模式非常像,只不过原型模式是保存的所有数据,实现了cloneable接口而备忘录模式,可以只对部分数据进行保存。