C++实现singleton(三种方法实现)

//单例模式最初的定义出现于《设计模式》(艾迪生维斯理, 1194):
//“保证一个类仅有一个实例,并提供一个访问它的全局访问点。”
#include   
#include "Poco\Mutex.h"  
//方法1:POCO库使用模板实现的,这个由很多缺陷,不推荐使用。可以与后面的几个比较来学习  
template     
class SingletonHolder    
    /// This is a helper template class for managing    
    /// singleton objects allocated on the heap.    
    /// The class ensures proper deletion (including    
    /// calling of the destructor) of singleton objects    
    /// when the application that created them terminates.    
{    
public:    
    SingletonHolder():    
        _pS(0)    
    /// Creates the SingletonHolder.    
    {    
    }    
    ~SingletonHolder()    
        /// Destroys the SingletonHolder and the singleton    
        /// object that it holds.    
    {    
        delete _pS;    
    }    
    S* get()    
        /// Returns a pointer to the singleton object    
        /// hold by the SingletonHolder. The first call    
        /// to get will create the singleton.    
    {    
        //加锁保证线程安全  
        Poco::FastMutex::ScopedLock lock(_m);    
        if (!_pS) _pS = new S;    
        return _pS;    
    }    
private:    
    S* _pS;    
    Poco::FastMutex _m;    
};  
//方法2:使用时创建  
class Singleton2  
{  
public:  
    static Singleton2*GetInstance()  
    {  
        //加锁,依据编译环境不同自己选择  
        if(NULL == m_Instance)  
           m_Instance = new Singleton2();  
        return m_Instance;  
        //解锁  
    }  
private:  
    static Singleton2 *m_Instance;//静态数据成员,保证该成员属于该类,而非类的具体对象  
    Singleton2(){}     //私有构造函数,外部不可见。  
    class Cargo       //内嵌类,在Singleton外部不可见,当Singleton被删除的时候,通过Cargo来delete  
    {  
    public:  
        ~Cargo()  
        {  
            if(m_Instance)  
               delete m_Instance;     
        }  
    };  
};  


//方法3:先创建好  
class Singleton3  
{  
public:  
    static Singleton3*GetInstance()  
    {  
      static Singleton3* Instance = NULL;   
        if(NULL == Instance)  
        {  
       Instance = new Singleton3();  
    }  
        return Instance;  
    }  
private:  
    Singleton3(){}     //私有构造函数,外部不可见。  
};
//方法4:下面是一个模板单例类  
template   
class Singleton  
{  
public:  
    //获取类的唯一实例  
    static inline T* instance();  
    //释放类的唯一实例  
    void release();  
protected:  
    Singleton(void){}  
    ~Singleton(void){}  
    static T* _instance;  
};  
  
template   
inline T* Singleton::instance()  
{  
    if(!_instance)  
    {  
        _instance = new T;  
    }  
    return _instance;  
}  
  
template   
void Singleton::release()  
{  
    if (!_instance)  
    {  
        return;  
    }  
    delete _instance;  
    _instance = 0;  
} 


//cpp文件中需要先声明静态变量
#define DECLARE_SINGLETON_MEMBER(_Ty)
template <> _Ty* Singleton<_Ty>::_instance = NULL;
#endif


你可能感兴趣的:(设计模式,C++)