在服务开发过程中,常常需要单例来保存全局资源,本文给出一个实用的实现方案。
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();