單例模式

題目:實現一個類,只能生成該類的一個實例

Release()函數:防止內存泄露;
私有的構造函數:生成唯一的一個實例;
私有的拷貝構造函數、私有的賦值操作符函數的申明:不違背單例模式的特性;

GetInstance()函數:公有的靜態方法去獲取唯一的實例--------------->static關鍵字確保全局的唯一性;
要使用多線程會出現問題:則需要增加互斥鎖lock(),unlock();互斥鎖需自己去實現;
由於每次去上鎖、開鎖會有很大的系統開銷問題,則在用if(instance == NULL)語句去判斷,只有當對象沒被創建之前纔去上鎖,反之不上鎖;

static Singleton* instance;:私有的靜態指針變量指向類的唯一實例,static關鍵字使得其與類關聯在一起;

Singleton* Singleton:: instance = NULL;:靜態數據成員必須在類的外部定義和初始化;且定義時不能重複static關鍵字,該關鍵字只出現在類內部的申明語句;

代碼如下:

class Singleton
{
private:
	static Singleton* instance;
private:
	Singleton()
	{}
	Singleton(const Singleton& sl);
	Singleton& operator=(const Singleton& sl);
public:
	static void Release()
	{
		if (instance != NULL)
		{
			delete[] instance;
			instance = NULL;
		}
	}
	static Singleton* GetInstance()
	{
		if (instance == NULL)
		{
			Lock();
			if (instance == NULL)
			{
				instance = new Singleton();
			}
			Unlock();
		}
		return instance;
	}
};
Singleton* Singleton:: instance = NULL;




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章