逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::

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);
posted on 2013-06-25 21:46 逛奔的蜗牛 阅读(1000) 评论(0)  编辑 收藏 引用 所属分类: C/C++Qt

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理