介绍
备忘录模式场景很常见,今天我们就来简单模拟,word文档记录文字后,每次备份,然后恢复备份是怎么实现的。
首先,我们需要3个角色,分布是文档本身、备份、保存备份的容器
- 文本本身:它具有添加内容、生成备份文件、还原备份文件3个功能
- 备份文件:它能存储文档中关键的细节。
- 保存备份的容器:它存储的各个时间段的备份文件,方便随时存取。
UML图
代码
- Document:这个是模拟的word文档
package com.bridge.memento;
public class Document {
private String value;
private String otherInfo = "这里模拟不需要备份的信息";
public void setValue(String value){
this.value = value;
}
public void SetMemento(Memento memento){
this.value = memento.getValue();
}
public Memento saveMemento(){
return new Memento(this.value);
}
@Override
public String toString() {
return "Document{" +
"value='" + value + '\'' +
'}';
}
public void show() {
System.out.println(toString());
}
}
- Memento:这个模拟的是word文档的备份
package com.bridge.memento;
public class Memento {
private String value;
public Memento(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
- DocumentCa retaker:这个模拟的是管理备份文件的容器
package com.bridge.memento;
import java.util.Stack;
public class DocumentCaretaker {
private Stack<Memento> documentStack = new Stack<>();
public void addDocument(Memento memento){
documentStack.push(memento);
}
public Memento getPrevison(){
if(documentStack.empty()){
return null;
}
return documentStack.pop();
}
}
- 这里模拟添加文字并备份,之后还原备份的过程
public class Demo {
public static void main(String[] args) {
DocumentCaretaker documentCaretaker = new DocumentCaretaker();//保存备忘录的容器
Document document = new Document();
document.setValue("你好!");//开始记录
documentCaretaker.addDocument(document.saveMemento());//当前Document的内容保存到Memento中,并添加备忘录到容器
document.setValue("你好!,我是Bridge。");//新的记录
documentCaretaker.addDocument(document.saveMemento());//当前Document的内容保存到Memento中,并添加备忘录到容器
document.setValue("你好!,我是Bridge。我来自四川!");//新的记录
documentCaretaker.addDocument(document.saveMemento());//当前Document的内容保存到Memento中,并添加备忘录到容器
document.setValue("你好!,我是Bridge。我来自四川!我热爱编程……");//新的记录
document.show(); //展示当前的内容
/* 下面开始还原 */
document.SetMemento(documentCaretaker.getPrevison()); //还原上一次的内容
document.show(); //展示当前的内容
document.SetMemento(documentCaretaker.getPrevison()); //还原上一次的内容
document.show(); //展示当前的内容
document.SetMemento(documentCaretaker.getPrevison()); //还原上一次的内容
document.show(); //展示当前的内容
}
}
- 打印结果
Document{value='你好!,我是Bridge。我来自四川!我热爱编程……'}
Document{value='你好!,我是Bridge。我来自四川!'}
Document{value='你好!,我是Bridge。'}
Document{value='你好!'}
总结
- 备忘录模式还是很简单的,文档和备份文件时依赖关系,而备份文件和备份的管理容器是聚会关系。
- 刚开始,我考虑过文档类和备份类是否可以依赖于接口,但发现文档类中的备份方法和还原备份方法需要强耦合与备份类,也就无法依赖于接口。
- 但是备份类和备份容器管理可以依赖于接口,大家如果业务有需要,可以考虑将他们依赖于接口实现。
- 备份类在实际开发中,可能会非常大,会导致备份容器过大,可以考虑将备份容器中的内容转移到数据库或者文件中。毕竟他是需要持久化的,不宜放入内存中。