单例模式的三种版本

 //版本一:静态对象+嵌套类
 class Singleton {
 private:
	 class AutoRelease
	 {
	 public:
		 AutoRelease()
		 {
			 cout << "AutoRelease()" << endl;
		 }
		 ~AutoRelease()
		 {
			 cout << "~AutoRelease()" << endl;
			 if (_pInstance)
			 {
				 delete _pInstance;
			 }
		 }
	 };
 public:
	 static Singleton *getInstance()
	 {
		 if (NULL == _pInstance) {
			 _pInstance = new Singleton;
		 }
		 return _pInstance;
	 }
 private:
	 Singleton() { cout << "Singleton()" << endl; }
	 ~Singleton() { cout << "~Singleton()" << endl; }
 private:
	 static Singleton *_pInstance;
	 static AutoRelease _auto;
 };


 //懒汉式/饿汉式
 Singleton *Singleton::_pInstance = NULL;//懒加载
 Singleton *Singleton::_pInstance=getInstance();//饱汉式
 Singleton::AutoRelease Singleton::_auto;
 //版本二  atexit+饱汉式
 class Singleton1 {
	 static Singleton1 *getInstance() {
		 if (NULL == _pInstance)
		 {
			 _pInstance = new Singleton1;
			 atexit(destroy);
		 }
		 return _pInstance;
	 }
	 static void destroy()
	 {
		 if (_pInstance)
			 delete _pInstance;
	 }
 private:
	 static Singleton1 *_pInstance;
	 Singleton1() { cout << "Singleton1()" << endl; }
	 ~Singleton1() { cout << "~Singleton1()" << endl; }


 private:
	 static Singleton1 *_pInstance;
 };
 Singleton1 *Singleton1::_pInstance = getInstance();//饱汉式,可以保证线程是安全的
 //版本三:让单例类对象自动释放
//atexit+phtnread_once
 class Singleton2
 {
 public:
	 static Singleton2 *getInstance()
	 {//能保证多线程安全
		 pthread_once(&_once, init);
		 return _pInstance;
	 }


	 static void init()
	 {
		 _pInstance = new Singleton2;
		 atexit(destory);
	 }
	 
	 static void destory()
	 {
		 if (_pInstance)
			 delete _pInstance;
	 }


 private:
	 Singleton2() { cout << "Singleton()" << endl; }
	 Singleton2() { cout << "~Singleton()" << endl; }
 private:
	 static Singleton2 *_pInstance;
	 static pthread_once_t _once;
 };
 Singleton2 *Singleton2::_pInstance = NULL;
 pthread_once_t Singleton2::_once = PTHREAD_ONCE_INIT;


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭