编辑:从另一个问题中,我提供了一个答案,该答案具有许多有关单身人士的问题/答案的链接:有关单身人士的更多信息,请参见:
因此,我读了Singletons主题:好的设计还是拐杖?
而且争论仍然很激烈。
我认为单例是一种设计模式(好的和坏的)。
Singleton的问题不是模式,而是用户(对不起每个人)。每个人和他们的父亲都认为他们可以正确实施一个方案(从我进行的许多访谈中,大多数人都做不到)。同样因为每个人都认为他们可以实现正确的Singleton,所以他们滥用Pattern并在不合适的情况下使用它(用Singletons代替全局变量!)。
因此,需要回答的主要问题是:
- 什么时候应该使用Singleton
- 您如何正确实现Singleton
我对本文的希望是,我们可以在一个地方(而不是谷歌和搜索多个站点)一起收集何时(然后如何)正确使用Singleton的权威来源。同样合适的是反使用和常见的不良实现的列表,这些列表解释了为什么它们无法正常工作以及对于好的实现而言它们的弱点。
所以滚了一下球:
我会举起我的手,说这是我用的,但可能有问题。
我喜欢他的“有效C ++”一书中对“斯科特·迈尔斯”的处理
使用单例的好情况(不多):
- 记录框架
- 线程回收池
/*
 * 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;
        }
};好。让我们将一些批评和其他实现放在一起。
:-)