您的位置:首页 > 其它

设计模式之单体模式

2015-06-06 11:33 211 查看
一,应用场景

全局范围内只生成一个对象,比如常见项目中的配置管理部分,通常就是一处初始化,全局使用。

单线程可以用单线程的模式,多线程就需要考虑到线程安全问题,可以借助pthread_once_t,pthread_mutex_t来实现线程安全

二,源码

包括单线程版本与线程安全版本,附简单的测试代码。

/*************************************************************************
> File Name: singlton.cpp
> Author:zhangtx
> Mail: 18510665908@163.com
> Created Time: 2015年06月06日 星期六 09时48分45秒
************************************************************************/
#include<iostream>
#include<pthread.h>
using namespace std;
class TestC
{
public:
TestC()
{
cout<<"TestC is constructed"<<endl;
}
void run()
{
cout<<pthread_self()<<endl;
}
};

#ifdef SINGLETHREAD
template <class T>
class Instance
{
private:
static T *m_value;
private:
Instance(){

};
~Instance(){

};
Instance(const Instance &instance)
{
}
Instance &operator=(const Instance &instance)
{
}
public:
static T * getInstance();
};

template<class T>
T * Instance<T>::m_value=NULL;

template<class T>
T *Instance<T>::getInstance()
{
if (m_value==NULL)
m_value=new T();
return m_value;
}

int main(int argc,char *argv[])
{
Instance<TestC>::getInstance();
Instance<TestC>::getInstance();
Instance<TestC>::getInstance();
}
#else

template<class T>
class Instance
{
private:
static T *m_value;
static pthread_once_t m_once;
private:
Instance()
{
};
~Instance()
{
};
Instance(const Instance &instance)
{
};
Instance &operator=(const Instance &instance)
{

}
static void init()
{
m_value=new T();
}
public:
static T *getInstance();
};
template<class T>
T * Instance<T>::m_value=NULL;
template<class T>
pthread_once_t Instance<T>::m_once=PTHREAD_ONCE_INIT;

template<class T>
T *Instance<T>::getInstance()
{
pthread_once(&m_once,&init);
return m_value;
}

void *ThreadFunc(void *)
{
while(true)
{
Instance<TestC>::getInstance()->run();
sleep(10);
}
}
int main(int argc,char *argv[])
{
int threadCount=5;

pthread_t tid[5];
for(int idx=0;idx<threadCount;idx++)
{
pthread_create(&tid[idx],NULL,&ThreadFunc,NULL);
}

for(int idx=0;idx<threadCount;idx++)
{
pthread_join(tid[idx],NULL);
}
return 0;
}

#endif

三,运行结果

多线程场景

[root@M-192-168-10-225 algo]# g++ singleSing.cpp  -lpthread
[root@M-192-168-10-225 algo]# ./a.out
TestC is constructed
139764064061184
139764053571328
139764043081472
139763940062976
139764032591616
139764053571328
139764064061184
139764032591616
139763940062976
139764043081472

单线程场景

[root@M-192-168-10-225 algo]# g++ singleSing.cpp
[root@M-192-168-10-225 algo]# ./a.out
TestC is constructed
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: