1. 程式人生 > >C++單例模式的五種實現

C++單例模式的五種實現

Singleton.h 

#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <mutex>
/****************************第一種實現*******************************************/

/*
懶漢
1.執行緒不安全
2.記憶體洩露
3.用到時被初始化
3.物件在堆中
*/
class CSingleton1
{
public:
	static CSingleton1* Instance();
private:
	CSingleton1(const CSingleton1&);
	CSingleton1 & operator =(const CSingleton1 &);
	static CSingleton1 * instance;
	CSingleton1();

};



/****************************第二種實現*******************************************/

/*
餓漢
1、一開始便初始化
2、解構函式完成垃圾回收
3、執行緒安全
4、物件在堆中
*/
class CSingleton2
{
public:
	static CSingleton2 * Instance();
	class CGarbo
	{
	public:
		~CGarbo();
	};

private:
	static CSingleton2 *instance;
	static CGarbo garbo;
};
/****************************第三種實現******************************************
1.一開始便初始化
2.物件在靜態區
3.程式結束時自動釋放靜態區的成員變數
4.執行緒安全
*/
class CSingleton3 
{
public:
	static CSingleton3 * Instance();
private:
	CSingleton3();
	static CSingleton3 instance;
};

/****************************第四種實現******************************************
1.執行時生成
2.執行緒安全
3.物件在堆中
4.程式結束自動釋放
*/
class CSingleton4
{
public:

	static CSingleton4 * Instance();
private:
	CSingleton4();
};

/****************************第五種實現******************************************
1.執行時生成
2.執行緒安全
3.物件在堆中
4.程式結束自動釋放
*/


class CSingleton5
{
public:
	static CSingleton5* Instance();
private:
	static CSingleton5* instance;
	static std::mutex mutex_;
	CSingleton5();
};
#endif // !_SINGLETON_H_

Singleton.cpp

#include <iostream>
#include "Singleton.h"

CSingleton1 * CSingleton1::Instance()
{
	if (instance == NULL)
	{
		instance = new CSingleton1();
	}
	return instance;
}
CSingleton1::CSingleton1()
{

}
//私有靜態成員變數要手動初始化
CSingleton1 * CSingleton1::instance = NULL;//此句一定要寫,否則會引起無法解析的外部符號錯誤



CSingleton2 * CSingleton2::Instance()
{
	return instance;
}

CSingleton2::CGarbo::~CGarbo()
{
	if (instance)
	{
		delete instance;
	}
}

CSingleton2 * CSingleton2::instance = new CSingleton2();
CSingleton2::CGarbo CSingleton2::garbo;

CSingleton3 * CSingleton3::Instance()
{
	return &instance;
}
CSingleton3::CSingleton3() {};

CSingleton3 CSingleton3::instance;

CSingleton4 * CSingleton4::Instance()
{
	static CSingleton4 instance;
	return &instance;
}
CSingleton4::CSingleton4() {};

CSingleton5::CSingleton5() {};
CSingleton5* CSingleton5::instance=NULL;
std::mutex CSingleton5::mutex_;
CSingleton5* CSingleton5::Instance()
{
	if (instance==NULL)
	{
		mutex_.lock();
		if (instance == NULL)//第二次
		{
			instance = new CSingleton5();
		}
		mutex_.unlock();
	}
	return instance;
}