Singleton mode Linux in C + + implementation of __ storage

Source: Internet
Author: User

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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.