我在另一个网站上的文章:
http://www.matrix.org.cn/thread.shtml?topicId=5c99e4e2-90d7-11dc-b8c0-a384f0e97a57&forumId=20
我刚开始学习设计模式,参考jdon的设计模式这本书,里面关于 Memento模式的例子如下(本人稍加修改):
1. 原始数据类
public class Originator {
protected int number = 0;
protected String file = null;
public Originator() {
}
public void setNumber(int number){
this.number = number;
}
public int getNumber(){
return number;
}
public void setFile(String file){
this.file = file;
}
public String getFile(){
return file;
}
// 创建一个Memento
public Memento getMemento() {
return new Memento(this);
}
// 恢复到原始值
public void setMemento(Memento m) {
number = m.number;
file = m.file;
}
}
2.储存类
public class Memento {
protected int number;
protected String file = null;
public Memento(Originator o) {
number = o.number;
file = o.file;
}
}
3.测试应用:
public void testMemento(){
Originator org = new Originator();
org.setNumber(10);
org.setFile("org_File");
Memento mem = new Memento(org);
org.setFile("new_File");
org.setNumber(20);
org.setMemento(mem);
assertEquals(org.getFile(),"org_File");
assertEquals(org.getNumber(),10);
}
测试ok! 可以恢复原来的值。页面应用中的session,还有数据层的持久层 感觉也用了这种方法。
缺点:如果数据量很大时,不仅写备份类不方便,而且也很耗费大,如果内部状态很多,再保存一份,无意要浪费大量内存.
想到以前学过的 Prototype 模式,结合如下:
1.原始类
public class Originator implements Cloneable {
protected int number = 0;
protected String file = null;
protected Originator org = null;//用于存储的类
public Originator() {
}
public void setNumber(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
public void setFile(String file) {
this.file = file;
}
public String getFile() {
return file;
}
//取出原始值
public Originator getOriginator() {
return org;
}
//恢复到原始值
public void setOriginator() {
org =(Originator)this.clone();
}
//prototype 方法
public Object clone() {
Object object = null;
try {
object = super.clone();
} catch (CloneNotSupportedException exception) {
System.err.println("Originator is not Cloneable");
}
return object;
}
}
2.测试类如下:
public void testPrototype(){
Originator org = new Originator();
org.setNumber(10);
org.setFile("org_File");
//Memento mem = new Memento(org);
org.setOriginator();//将原数据放入存储类中
org.setFile("new_File");
org.setNumber(20);
///org.setMemento(mem);
org.getOriginator();//得到原来值
///org.setMemento(mem);
assertEquals(org.getOriginator().getFile(),"org_File");
assertEquals(org.getOriginator().getNumber(),10);
}