本帖最后由 小江哥 于 2019-6-16 09:40 编辑
我们知道单利模式可以确保在系统中只存在唯一实例,不过当序列化遇到单例时,里边就有了个问题:从内存读出而组装的对象破坏了单例的规则。为了解决这个问题提供一下两种解决方案:
- 单利类1
- public class Singleton implements Serializable {
- private Singleton() {
- System.out.println("实例化");
- }
- private static class LazyHolder {
- static final Singleton INSTANCE = new Singleton();
- }
- public static Singleton getInstance() {
- return LazyHolder.INSTANCE;
- }
- private Object readResolve(){
- return LazyHolder.INSTANCE;
- }
- }
复制代码[Java] 纯文本查看 复制代码 public enum EmpsStatus implements Serializable {
LOGIN(100,"用户登录");
private Integer code;
private String msg;
private EmpsStatus(Integer code,String msg) {
this.code=code;
this.msg=msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
测试代码:
- public class MainTest {
- @Test
- public void test()throws Exception {
- Singleton s1=null;
- Singleton s = Singleton.getInstance();
- //先将实例串行化到文件
- FileOutputStream fos=new FileOutputStream("sersingleton.txt");
- ObjectOutputStream oos=new ObjectOutputStream(fos);
- oos.writeObject(s);
- oos.flush();
- oos.close();
- //从文件读出原有的单例类
- FileInputStream fis =new FileInputStream("Sersingleton.txt");
- ObjectInputStream ois=new ObjectInputStream(fis);
- s1=(Singleton)ois.readObject();
- Assert.assertEquals(s,s1);
- }
- @Test
- public void test2()throws Exception {
- FileOutputStream fos=new FileOutputStream("sersingleton.txt");
- ObjectOutputStream oos=new ObjectOutputStream(fos);
- oos.writeObject(EmpsStatus.LOGIN);
- oos.flush();
- oos.close();
- FileInputStream fis =new FileInputStream("Sersingleton.txt");
- ObjectInputStream ois=new ObjectInputStream(fis);
- EmpsStatus e =(EmpsStatus)ois.readObject();
- Assert.assertEquals(EmpsStatus.LOGIN,e);
- }
- }
复制代码
|