且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单例模式(Bill Pugh 的解决方案)

更新时间:2023-01-15 10:51:26

我认为 Pugh 先生的版本受到高度重视,因为它只在 getInstance() 被调用时才执行单例的实例化,即不是在加载类(持有 getInstance 方法的类)时.如果您的单例结构做了一些昂贵的事情,那么这对您来说可能是一个优势.如果您像世界上大多数人一样,单例只是为了避免静态方法(并且您还没有转向依赖注入框架),那么我不会为此失眠.

I think Mr Pugh's version is held in high regard because it only performs the instantiation of the singleton when getInstance() is called i.e. not when the class (the class holding the getInstance method) is loaded. If your singleton construction does something costly then this may be an advantage for you. If you're like the majority of the world whose singletons are just to avoid static methods (and you haven't moved onto dependency injection frameworks), then I would not lose any sleep over it.

正如文章所述,Pugh 先生的方法比静态实例变量更懒惰 - 但实际上,如果加载了 Singleton 类,您无论如何都会调用 getInstance 方法.因此,作为一项计算机科学练习,它很有用,但在现实世界中,它的好处值得商榷.

As the article states, Mr Pugh's method is lazier than the static instance variable - but in reality if the Singleton class gets loaded you're going to be calling the getInstance method anyhow. So as a computer science exercise it's useful, but in the real world its benefits are debatable.

附言我不太关心 Bloch 先生在这里的例子,因为使用枚举就是说 My Singleton IS-A 枚举,这对我来说听起来不正确(尤其是对于那些说永远不会实现接口只是为了得到常数)

p.s. I don't care much for Mr Bloch's example here as to use an enum would be to say My Singleton IS-A enum, which doesn't sound right to me (especially from someone who, rightly, says never implement an interface just to get the constants)