本文介绍了单身人士:好设计还是拐杖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请提供您的意见的理由,而不仅仅是单身人士是为了懒惰的程序员!



这是一个相当不错的文章,虽然这是反对使用Singletons:



有没有人有任何其他好的文章呢?可能支持单身人士?

解决方案

在单身人士的辩护中:




  • 它们不如全局变量,因为全局变量没有标准强制的初始化顺序,并且您可以轻松地看到由于天真或意外的依赖性顺序引起的非确定性错误。 Singletons(假设它们分配在堆上)是在所有全局变量之后创建的,并且在代码中非常可预测的地方。

  • 它们对资源懒惰非常有用/ -caching systems ,例如缓慢的I / O设备的接口。如果您智能地构建了一个单一的接口,缓慢的设备,没有人会打电话,你不会浪费任何时间。如果另一段代码从多个地方调用,您的单例可以同时优化缓存,并避免任何双重查询。您也可以轻松地避免单身控制资源中的任何死锁情况。



反对单身人士:




  • 在C ++中,没有很好的方法可以在单身人士之后进行自动清理。有一些解决方法,还有一些简单的方式来做,但是,只有一个简单而通用的方式来确保你的单例的析构函数始终被调用。这不是那么可怕的记忆 - 只是把它看作是更多的全局变量,为此目的。但是,如果您的单身人士分配其他资源(例如锁定某些文件)并且不会释放它们,那么可能会很糟糕。



我自己的意见:



我使用单身人士,但如果有合理的选择,可以避免他们。这对我来说已经很好了,我发现他们是可测试的,虽然稍微要多一点测试。


Singletons are a hotly debated design pattern, so I am interested in what the Stack Overflow community thought about them.

Please provide reasons for your opinions, not just "Singletons are for lazy programmers!"

Here is a fairly good article on the issue, although it is against the use of Singletons:scientificninja.com: performant-singletons.

Does anyone have any other good articles on them? Maybe in support of Singletons?

解决方案

In defense of singletons:

  • They are not as bad as globals because globals have no standard-enforced initialization order, and you could easily see nondeterministic bugs due to naive or unexpected dependency orders. Singletons (assuming they're allocated on the heap) are created after all globals, and in a very predictable place in the code.
  • They're very useful for resource-lazy / -caching systems such as an interface to a slow I/O device. If you intelligently build a singleton interface to a slow device, and no one ever calls it, you won't waste any time. If another piece of code calls it from multiple places, your singleton can optimize caching for both simultaneously, and avoid any double look-ups. You can also easily avoid any deadlock condition on the singleton-controlled resource.

Against singletons:

  • In C++, there's no nice way to auto-clean-up after singletons. There are work-arounds, and slightly hacky ways to do it, but there's just no simple, universal way to make sure your singleton's destructor is always called. This isn't so terrible memory-wise -- just think of it as more global variables, for this purpose. But it can be bad if your singleton allocates other resources (e.g. locks some files) and doesn't release them.

My own opinion:

I use singletons, but avoid them if there's a reasonable alternative. This has worked well for me so far, and I have found them to be testable, although slightly more work to test.

这篇关于单身人士:好设计还是拐杖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:03