第一篇 生成及初始化对象 第六章 - 备忘录模式
借助建造方法和原型方法提供的便利,可以轻松实现对象信息的备份与恢复。
来看例子。
// 秋思
public class QiuSi implements Cloneable {
private String a, b, c, x, y, z;
private QiuSi bak;// 备份对象
// 建造方法(1)
public QiuSi first(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
return this;
}
// 建造方法(2)
public QiuSi second(String x, String y, String z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
// 原型方法
@Override
public QiuSi clone() throws CloneNotSupportedException {
return (QiuSi) super.clone();
}
// 备份
public void backup() throws Exception {
this.bak = this.clone();
}
// 恢复
public void restore() {
this.first(bak.a, bak.b, bak.c)
.second(bak.x, bak.y, bak.z);
}
/* Getters and Setters */
}
此处的备份对象bak起到了“备忘录”的作用,它可以存储对象快照,以备查证或恢复数据。
使用效果如下。
// 测试类
public class Test {
public void test() throws Exception {
// 生成对象
QiuSi obj = new QiuSi();
// 初始化
obj.first("枯藤", "老树", "昏鸦")
.second("小桥", "流水", "人家");
// 备份
obj.backup();
// 修改信息
obj.first("孤村", "落日", "残霞")
.second("轻烟", "老树", "寒鸦");
// 恢复
obj.restore();
}
}
浙公网安备 33010602011771号