美文网首页
Item 3: Enforce the singleton pr

Item 3: Enforce the singleton pr

作者: 空谷幽心 | 来源:发表于2018-07-30 14:25 被阅读17次

笔记

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

理解与思考

相关文章

网友评论

      本文标题:Item 3: Enforce the singleton pr

      本文链接:https://www.haomeiwen.com/subject/giaxvftx.html