2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 设计模式之单体模式

设计模式之单体模式

时间:2024-01-12 17:26:08

相关推荐

设计模式之单体模式

一,应用场景

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

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

二,源码

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

/*************************************************************************> File Name: singlton.cpp> Author:zhangtx> Mail: 18510665908@ > Created Time: 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 SINGLETHREADtemplate <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();}#elsetemplate<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.outTestC is constructed139764064061184139764053571328139764043081472139763940062976139764032591616139764053571328

139764064061184139764032591616

139763940062976139764043081472

单线程场景

[root@M-192-168-10-225 algo]# g++ singleSing.cpp [root@M-192-168-10-225 algo]# ./a.outTestC is constructed

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。