Correct implementation of initialization-on-demand holder idiom

前端 未结 3 988
轮回少年
轮回少年 2020-12-10 12:36

I have got two versions of \"Initialization-on-demand holder idiom\":

  1. http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
  2. http://en.wik
3条回答
  •  醉梦人生
    2020-12-10 13:25

    I use number 1 (private INSTANCE) because you generally try to use the narrowest scope as possible. But in this case since the Holder class is private it doesn't really matter. However, suppose someone later decided to make the Holder class public then number 2 could be problematic from an encapsulation perspective (callers could bypass the getInstance() method and access the static field directly).

提交回复
热议问题