单身人格(Bill Pugh的解决方案) [英] Singleton pattern (Bill Pugh's solution)

查看:96
本文介绍了单身人格(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.

所以要简单的说:

So to make it simple: Why is Bill Pugh's solution better than the example above?

是因为在实际使用虚拟机之前不会由静态类加载静态类,这样的事情,所以我们不要在我们转到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.

p.s。我不在乎布洛赫先生的榜样,因为使用枚举将是说我的单身人士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天全站免登陆