单例模式(Bill Pugh 的解决方案) [英] Singleton pattern (Bill Pugh's solution)

查看:27
本文介绍了单例模式(Bill Pugh 的解决方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于单例模式的维基,但我不确定我是否理解这一点:https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom 部分正确.

I'm reading wiki about the singleton pattern and I'm not sure if I understand this: https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom part of it correctly.

简单来说:为什么 Bill Pugh 的解决方案比上面的例子更好?

是不是因为静态类在实际使用之前没有被VM加载或类似的东西,所以我们在转向getInstance()方法之前不创建对象?该方法线程是否仅在初始化对象的范围内是安全的?

Is it because a static class is not load by the VM before it's actually used or something like this, so we don't create the object before we turn to the getInstance() method? Also is that method thread safe only to the extent of initializing the object?

推荐答案

我认为 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)

这篇关于单例模式(Bill Pugh 的解决方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆