Singleton模式Linux下的C++实现

        Singleton模式是最常用的设计之一,最近结合自己的实际应用,把Singleton作为模板抽象出来(线程安全),权当抛砖引用,欢迎大家提出批评意见,互相交流。下面为源码,已经编译运行过。


Singleton 模板类

#ifndef _Singleton_h_
#define _Singleton_h_

#include <pthread.h>
class Mutex
{
public:
	Mutex()
	{
		pthread_mutex_init(&m_lock,NULL);
	}

	~Mutex()
	{
		pthread_mutex_destroy(&m_lock);
	}

	void Lock()
	{
		pthread_mutex_lock(&m_lock);
	}

	void UnLock()
	{
		pthread_mutex_unlock(&m_lock);
	}

private:
	pthread_mutex_t m_lock;
};

template<class T>
class Singleton
{
public:
	static T*    GetInstance();
        static void  Destroy();
private:
	static T*    m_pInstance;
        static Mutex m_mutex;
};

template<class T>
T* Singleton<T>::m_pInstance = 0;

template<class T>
Mutex Singleton<T>::m_mutex;

template<class T>
T* Singleton<T>::GetInstance()
{
	if (m_pInstance)
	{
		return m_pInstance;
	}
	m_mutex.Lock();
	if (NULL == m_pInstance)
	{
		m_pInstance = new T;
	}
	m_mutex.UnLock();
	return m_pInstance;
}

template<class T>
void Singleton<T>::Destroy()
{
	if (m_pInstance)
	{
		delete m_pInstance;
		m_pInstance= NULL;
	}
}

#endif


验证程序

#include "Singleton.h"
#include <iostream>
using namespace std;

class Testclass
{
public:
	void Run ()
	{
		cout<<"Hi, Testclass run.\n";
	}
private:
        friend class Singleton<Testclass>;
        Testclass()  {};
        ~Testclass() {};
        Testclass(const Testclass& ref);
        Testclass& operator=(const Testclass& ref);
};

typedef Singleton<Testclass> SingleTestclass;

int main()
{
	Testclass* pInstance = SingleTestclass::GetInstance();
	pInstance->Run();
	return 0;
}


你可能感兴趣的:(C++,linux,null,delete,Class)