From: http://zh.wikipedia.org/wiki/单例模式
在C++编程语言中,单例模式应用的例子如下述代码所示(这里仅仅提供一个示例,这个例子对多线程的情况并不是安全的):
// ...
class lock
{
public:
lock();
lock(lock const & l);
~lock();
lock & operator =(lock const & l);
void request();
void release();
// ...
};
lock::lock()
{
// ...
}
// ...
lock::~lock()
{
// ...
}
// ...
void lock::request()
{
// ...
}
void lock::release()
{
// ...
}
// ...
// assumes _DATA_TYPE_ has a default constructor
template<typename _DATA_TYPE_>
class singleton
{
public:
static _DATA_TYPE_ * request();
static void release();
private:
singleton();
singleton(singleton<_DATA_TYPE_> const & s);
~singleton();
singleton<_DATA_TYPE_> & operator =(singleton<_DATA_TYPE_> const & s);
static _DATA_TYPE_ * pointer;
static lock mutex;
// ...
};
template<typename _DATA_TYPE_>
_DATA_TYPE_ * singleton<_DATA_TYPE_>::pointer = 0;
template<typename _DATA_TYPE_>
lock singleton<_DATA_TYPE_>::mutex;
template<typename _DATA_TYPE_>
_DATA_TYPE_ * singleton<_DATA_TYPE_>::request()
{
if(singleton<_DATA_TYPE_>::pointer == 0)
{
singleton<_DATA_TYPE_>::mutex.request();
if(singleton<_DATA_TYPE_>::pointer == 0)
{
singleton<_DATA_TYPE_>::pointer = new _DATA_TYPE_;
}
singleton<_DATA_TYPE_>::mutex.release();
}
return singleton<_DATA_TYPE_>::pointer;
}
template<typename _DATA_TYPE_>
void singleton<_DATA_TYPE_>::release()
{
if(singleton<_DATA_TYPE_>::pointer != 0)
{
singleton<_DATA_TYPE_>::mutex.request();
if(singleton<_DATA_TYPE_>::pointer != 0)
{
delete singleton<_DATA_TYPE_>::pointer;
singleton<_DATA_TYPE_>::pointer = 0;
}
singleton<_DATA_TYPE_>::mutex.release();
}
}
template<typename _DATA_TYPE_>
singleton<_DATA_TYPE_>::singleton()
{
// ...
}
// ...
int main()
{
int * s;
s = singleton<int>::request();
// ...
singleton<int>::release();
return 0;
}
@import url(http://www.cppblog.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);