序列化与反序列化的单例模式实现

ε祈祈猫儿з 提交于 2020-02-27 05:40:43

静态内置类可以达到线程安全的问题,但如果遇到序列化对象时,使用默认的方式运行得到的结果还是多例的。

import java.io.Serializable;

public class MyObject implements Serializable {

    private static final long serialVersionUID = 888L;
    private static class MyObjectHandler{
        private static final MyObject myObject = new MyObject();
    }

    public MyObject() {
    }

    public static MyObject getInstance(){
        return MyObjectHandler.myObject;
    }
    protected Object readResolve(){
        System.out.println("调用了readResolve方法!");
        return MyObjectHandler.myObject;
    }
}
import java.io.*;

public class SaveAndRead {

    public static void main(String[] args) {
        try {
            MyObject myObject =  MyObject.getInstance();
            FileOutputStream fosRef = new FileOutputStream(new File("D:\\data.txt"));
            ObjectOutputStream oosRef = new ObjectOutputStream(fosRef);
            oosRef.writeObject(myObject);
            System.out.println(myObject.hashCode());
            oosRef.close();
            fosRef.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            FileInputStream fisRef = new FileInputStream(new File("D:\\data.txt"));
            ObjectInputStream iosRef = new ObjectInputStream(fisRef);
            MyObject myObject = (MyObject) iosRef.readObject();
            iosRef.close();
            fisRef.close();
            System.out.println(myObject.hashCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

下一节:使用static代码块实现单例模式

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!