思想:

 

  一个单例类,无论采取哪一种设计(单元素枚举类除外), 一旦间接或者直接实现 Serializable 接口,为了保证单例,就要多增加一点考虑:保证类在反序列化之后能够保证单例。

 

public final class SerializableSingletonFail implements Serializable {

    private static final long serialVersionUID = 3355486892283807446L;

    private static final SerializableSingletonFail instance = new SerializableSingletonFail();

    private SerializableSingletonFail() {
        if (instance != null) {
            throw new IllegalStateException();
        }
    }

    public static final SerializableSingletonFail getInstance() {
        return instance;
    }

}

 

  以上是一个单例的简单饿汉模式实现,实现了 Serializable 接口。从类名上也不难看出,这是个错误示例。

 

  每一个类中,有两个很特殊的方法,分别是 writeReplace() 和 readResolve() 。

  前者保证,无论从什么对象序列化,只要是序列化这个类,都会把 writeReplace() 的返回对象序列化进文件;

  后者保证,无论从什么文件反序列化,都会反序列化成 readResolve() 的返回对象。

  这两个方法,对于方法签名有着严格的限定,包括入参(没有入参)和返回类型(Object),但是可以接受抛出不同的异常。

  建议将这两个方法的控制符设为 private,防止外部类的误操作。

 

public final class SerializableSingleton implements Serializable {

    private static final long serialVersionUID = -6451544700567522443L;

    private static final SerializableSingleton instance = new SerializableSingleton();

    private SerializableSingleton() {
        if (instance != null) {
            throw new IllegalStateException();
        }
    }

    public static final SerializableSingleton getInstance() {
        return instance;
    }

    private Object readResolve() {
        return instance;
    }

}

 

相关文章:

  • 2021-08-16
  • 2022-12-23
  • 2021-04-23
  • 2021-10-29
  • 2022-01-06
  • 2022-02-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-17
  • 2021-11-30
  • 2022-02-27
  • 2021-09-08
  • 2022-12-23
  • 2021-10-28
  • 2022-02-05
相关资源
相似解决方案