当前位置 > it书童 > java > 正文

序列化破坏单例模式原理解析

java it书童 2020-12-26 21:15:26 0赞 0踩 99阅读 0评论

序列化后再反序列化,还是同个对象吗?

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

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

        File file = new File("singleton_file");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

        HungrySingleton newInstance = (HungrySingleton) ois.readObject();
        System.out.println(instance);
        System.out.println(newInstance);
        System.out.println(instance == newInstance);
    }
}

结果:

design.pattern.creational.singleton.HungrySingleton@372f7a8d
design.pattern.creational.singleton.HungrySingleton@6f539caf
false

由此可见,序列化后再还原已经不是原来的对象,这就违背了单例模式的初衷

解决:在 HungrySingleton 类添加以下方法

private Object readResolve() {
    return hungrySingleton;
}

再测试:

design.pattern.creational.singleton.HungrySingleton@372f7a8d
design.pattern.creational.singleton.HungrySingleton@372f7a8d
true

具体原理需要断点进 jdk 源码查看

虽然最终返回的还是同个对象,但实际也进行了一次新实例化,只是没有返回

详细可参考 https://juejin.cn/post/6844903745772339214

关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
转载须注明出处:https://www.itshutong.com/articles/1012