Item 3: Enforce the singleton property with a private constructor or an enum type

笔记

  • 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方法返回单例对象。

理解与思考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容