很好的设计-安全的单例模式

在服务开发过程中,常常需要单例来保存全局资源,本文给出一个实用的实现方案。

 

template<class T>
class Singleton
{
    public:
        static T* instance()
        {
            if (NULL == instance_)
            {
                pthread_mutex_init(&mutex_, NULL);
                pthread_mutex_lock(&mutex_);
                if (NULL == instance_) {
                    instance_ = new T;
                }
                pthread_mutex_unlock(&mutex_);
            }   
            return instance_;
        }   
    protected:
        Singleton(){}
        virtual ~Singleton()
        {//虚析构函数,想想为啥呢?
            if (NULL != instance_)
            {
                delete instance_;
                instance_ = NULL;
            }
        }
        Singleton(const Singleton& single);//禁用拷贝和赋值函数
        Singleton& operator= (const Singleton& single);


    protected:
        static T* instance_;
        static pthread_mutex_t mutex_;
};

template<class T> T* Singleton<T>::instance_ = NULL;
template<class T> pthread_mutex_t Singleton<T>::mutex_;

  

使用:

 

class WorkerPool : public Singleton<WorkerPool> {
//methods & variables
};
WorkerPool* pool = WorkerPool::instance();

  

posted @ 2013-12-18 17:23  春文秋武  阅读(117)  评论(0编辑  收藏  举报