單例模式的C++簡單實現

一、懶漢模式

具體例子如下:

/**
  *		懶漢式單例模式
  */

#include <iostream>

using namespace std;

/* 定義Singleton類,用來表示單例模式 */
class Singleton
{
public:
	static Singleton *getInstance();
private:
	Singleton();
	Singleton(const Singleton &other);
	Singleton &operator=(const Singleton &other);

	static Singleton *instance;
};

/* 實現Singleton類中的方法和靜態數據成員 */
Singleton *Singleton::getInstance()
{
	return instance;
}

Singleton::Singleton(){cout << "Singleton()" << endl;}
Singleton::Singleton(const Singleton &other){cout << "Singleton(const Singleton &other)" << endl;}
Singleton &Singleton::operator=(const Singleton &other){cout << "Singleton &operator=(const Singleton &other)" << endl;}

Singleton *Singleton::instance = new Singleton();


/* 程序入口 */
int main()
{
	Singleton* s1 = Singleton::getInstance();
	Singleton* s2 = Singleton::getInstance();
	Singleton* s3 = Singleton::getInstance();

	cout << "s1 address is " << s1 << endl;
	cout << "s2 address is " << s2 << endl;
	cout << "s3 address is " << s3 << endl;
	
	return 0;
}
注意有內存泄漏。

二、餓漢模式

具體實現如下:

/**
  *	餓漢式單例模式
  */

#include <iostream>
#include <pthread.h>

using namespace std;

/* 定義Singleton類,用來表示單例模式 */
class Singleton
{
public:
	static Singleton *getInstance();
private:
	Singleton();
	Singleton(const Singleton &other);
	Singleton &operator=(const Singleton &other);

	static Singleton *instance;
	static pthread_mutex_t mutex;

	/* 定義一個內嵌類用於清除Singleton實例 */
	class DestroySingleton
	{
	public:
		~DestroySingleton();
	};

	static DestroySingleton destroyInstance;
};

/* 實現Singleton類中的方法和靜態數據成員 */
Singleton *Singleton::getInstance()
{
	if(NULL == instance)
	{
		pthread_mutex_lock(&mutex);			/* 上鎖 */
		if(NULL == instance)
		{
			instance = new Singleton();
		}
		pthread_mutex_unlock(&mutex);		/* 解鎖 */
	}
	return instance;
}

Singleton::Singleton(){cout << "Singleton()" << endl;}
Singleton::Singleton(const Singleton &other){cout << "Singleton(const Singleton &other)" << endl;}
Singleton &Singleton::operator=(const Singleton &other){cout << "Singleton &operator=(const Singleton &other)" << endl;}

Singleton *Singleton::instance = NULL;
pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;
Singleton::DestroySingleton Singleton::destroyInstance;


/* 實現內部類DestroySingleton的析構函數 */
Singleton::DestroySingleton::~DestroySingleton()
{
	if(NULL != Singleton::instance)
	{
		delete Singleton::instance;
		Singleton::instance = NULL;		/* 防止野指針 */
		cout << "~DestroySingleton()" << endl;
	}
}


/* 程序入口 */
int main()
{
	Singleton* s1 = Singleton::getInstance();
	Singleton* s2 = Singleton::getInstance();
	Singleton* s3 = Singleton::getInstance();

	cout << "s1 address is " << s1 << endl;
	cout << "s2 address is " << s2 << endl;
	cout << "s3 address is " << s3 << endl;
	
	return 0;
}
注意多線程的同步問題,加鎖與解鎖。
發佈了83 篇原創文章 · 獲贊 75 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章