序列化破坏单例模式原理解析及解决方案

  将单例对象序列化和反序列化操作后得到的新对象与原单例对象并不相同,因为反序列化是通过反射获取的新对象。

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton_file"));
        oos.writeObject(hungrySingleton);

        File file = new File("singleton_file");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        HungrySingleton newHungrySingleton = (HungrySingleton) ois.readObject();

        System.out.println(hungrySingleton);
        System.out.println(newHungrySingleton);
        System.out.println(hungrySingleton==newHungrySingleton);
    }
}

输出结果:
  designmodel.singleton.HungrySingleton@1d44bcfa
  designmodel.singleton.HungrySingleton@b4c966a
  false

  但是可以通过在单例类中添加readResolve方法解决该问题,但是该单例类必须实现SerializableExternalizable接口。

public class HungrySingleton implements Serializable {
    private static final HungrySingleton hungrySingleton;
    static {
        hungrySingleton = new HungrySingleton();
    }

    public static HungrySingleton getInstance(){
        return hungrySingleton;
    }

    private Object readResolve(){
        return hungrySingleton;
    }
}  

  readResolve方法并不是重写Object类中的方法,具体实现的原理可从源码中得到解释。

/**
     * Returns true if represented class is serializable or externalizable and
     * defines a conformant readResolve method.  Otherwise, returns false.
     */
    boolean hasReadResolveMethod() {
        requireInitialized();
        return (readResolveMethod != null);
    }  

输出结果:
  designmodel.singleton.HungrySingleton@1d44bcfa
  designmodel.singleton.HungrySingleton@1d44bcfa
  true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值