备忘录模式是指在不破坏对象本身的情况下将对象某一时刻的信息持久化。以便于以后可以恢复
在Java中,要被持久化的类需要实现Serializable接口
/**
* 需要被保存的对象
* */
public class Person implements Serializable {
String name = "小明";
int age = 20;
}
/***
*工具类
*/
public class Util {
//序列化
static String str = "D:\\study\\23种设计模式\\备忘录模式_Memento\\Person.data";
public static void save(Object o){
File f = new File(str);
try {
ObjectOutputStream ops = new ObjectOutputStream(new FileOutputStream(f));
ops.writeObject(o);
ops.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//反序列化
public static Object load(){
File f = new File(str);
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object o = ois.readObject();
return o;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.age = 21;
Util.save(p);
p.age = 22;
p=(Person) Util.load();
System.out.println(p.age);
}
}
执行结果:
21
可以看到,对象的状态通过save()方法保存了,又通过load()方法恢复了状态,指定目录下就有了存储文件