编辑: 从另一个问题中,我提供了一个答案,其中包含许多关于单例的问题/答案的链接:More info about singletons here:
所以我已经阅读了帖子 Singletons: good design or a crutch?
争论仍在继续。
我将单例视为一种设计模式(好的和坏的)。
Singleton 的问题不在于模式,而在于用户(对不起大家)。每个人和他们的父亲都认为他们可以正确地实现一项(根据我所做的许多采访,大多数人都不能)。同样因为每个人都认为他们可以实现正确的单例,所以他们滥用模式并在不合适的情况下使用它(用单例替换全局变量!)。
所以需要回答的主要问题是:
我对这篇文章的希望是,我们可以在一个地方(而不是必须用谷歌搜索多个站点)收集有关何时(以及如何)正确使用 Singleton 的权威来源。同样合适的是反使用和常见不良实现的列表,解释它们为什么无法工作以及好的实现它们的弱点。
所以开始吧:
我会举手说这是我用的,但可能有问题。
我喜欢“Scott Myers”在他的书“Effective C++”中对主题的处理
Good Situations to use Singletons (not many):
- Logging frameworks
- Thread recycling pools
/*
* C++ Singleton
* Limitation: Single Threaded Design
* See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
* For problems associated with locking in multi threaded applications
*
* Limitation:
* If you use this Singleton (A) within a destructor of another Singleton (B)
* This Singleton (A) must be fully constructed before the constructor of (B)
* is called.
*/
class MySingleton
{
private:
// Private Constructor
MySingleton();
// Stop the compiler generating methods of copy the object
MySingleton(MySingleton const& copy); // Not Implemented
MySingleton& operator=(MySingleton const& copy); // Not Implemented
public:
static MySingleton& getInstance()
{
// The only instance
// Guaranteed to be lazy initialized
// Guaranteed that it will be destroyed correctly
static MySingleton instance;
return instance;
}
};
好的。让我们一起来批评一下和其他实现。
:-)
最佳答案
答案:
在以下情况下使用单例:
在以下情况下不要使用单例:
如何创建最好的单例:
https://stackoverflow.com/questions/86582/