之前对单例比较熟悉,现在了解到可继承的单例类,记录下来,以防忘记。
1.一直以来忽略单例的析构的问题,平时用惯了第二种写单例的方法,但是没有想过这样用的好处
方法一:
class CSingleton
{
public:
static CSingleton* GetInstance();
private:
CSingleton(){};
static CSingleton * m_pInstance;
class CGarbo //它的唯一工作就是在析构函数中删除CSingleton的实例
{
public:
~CGarbo()
{
if( CSingleton::m_pInstance )
delete CSingleton::m_pInstance;
}
}
Static CGabor Garbo; //定义一个静态成员,程序结束时,系统会自动调用它的析构函数
};
方法二:
class CSingleton
{
//其他成员
public:
static Singleton *GetInstance() //使用局部变量的方法
{
static Singleton *instance = new singleton();
return instance;
}
private:
Singleton() {};
};
(2)多线程的单例类:
class Singleton
{
public:
static Singleton& GetInstance();
private:
Singleton();
~Singleton();
/* Use auto_ptr to make sure that the allocated memory for instance
** will be released when program exits (after main() ends).
*/
static std::auto_ptr<Singleton> s_instance;
friend class std::auto_ptr<Singleton>;
Singleton(const Singleton&);
Singleton& operator =(const Singleton&);
};
(3) 可继承的单例类:
template <typename T>
class ISingleton
{
public:
static T& GetInstance() {
static boost::mutex s_mutex; if (s_instance.get() == NULL) {
boost::mutex::scoped_lock lock(s_mutex);
if (s_instance.get() == NULL) {
s_instance.reset(new T());
} // 'lock' will be destructed now. 's_mutex' will be unlocked.
}
return *s_instance;
}
protected:
ISingleton() { }
~ISingleton() { }
// Use auto_ptr to make sure that the allocated memory for instance
// will be released when program exits (after main() ends).
static std::auto_ptr<T> s_instance;
private: ISingleton(const Singleton&);
ISingleton& operator =(const ISingleton&);
};
template <typename T>
std::auto_ptr<T> ISingleton<T>::s_instance;
//子类
class MySingleton : public ISingleton<MySingleton>
{
public: // blah blah
private:
MySingleton() {
cout << "Construct MySingleton" << endl;
}
~MySingleton() { c
out << "Destruct MySingleton" << endl;
}
friend ISingleton<MySingleton>;
friend class auto_ptr<MySingleton>;
MySingleton(const MySingleton&);
MySingleton& operator =(const MySingleton&);
};