Singleton mode is one of the most commonly used design, recently combined with its own practical applications, the singleton as a template abstraction (thread safety), the right to throw bricks as a reference, welcome to comment on the comments, mutual exchange. The following is the source code, has been compiled run.
Singleton template class
#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>::D Estroy () {if (m_pinstance) {delete m_pinstance; M_pinstAnce= NULL;
}} #endif
Validation Program
#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;
}