• 设计模式(一)单例模式:实现 Serializable 接口之后的额外操作


    思想:

      一个单例类,无论采取哪一种设计(单元素枚举类除外), 一旦间接或者直接实现 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;
        }
    
    }
  • 相关阅读:
    数据库sql常见优化方法
    String字符串创建与存储机制
    ==运算符和equals()方法的区别
    Math类中round、ceil和floor方法的功能
    String、StringBuffer和StringBuilder类的区别
    Flask 系列之 构建 Swagger UI 风格的 WebAPI
    Docker 系列之 常用镜像
    Docker 系列之 基础入门
    在 DotNetCore 3.0 程序中使用通用协议方式启动文件关联应用
    .NET Framework VS .NET Core
  • 原文地址:https://www.cnblogs.com/jing-an-feng-shao/p/7501812.html
Copyright © 2020-2023  润新知