笔记
Making a class a singleton can make it difficult to test its clients because it’s impossible to substitute a mock
implementation for a singleton unless it implements an interface that serves as its type.
不好测试,没法mock。There are two common ways to implement singletons. Both are based on keeping the constructor private and exporting a public static member to provide access to the sole instance.
创建单例的常用方法:1. public final static常量属性。 2. private static常量属性加public static访问方法。To maintain the singleton guarantee, declare all instance fields transient and provide a readResolve method (Item 89).
单例在涉及到序列化和反序列化的时候要注意维护实例的全局单一性。可以给对象属性加transient
修饰符,然后覆写readResolve
方法返回单例对象。