用继承的方式实现 结构较清晰
#ifndef __SINGLETION_H__
#define __SINGLETION_H__
template<class T>
class CSingletion
{
public:
virtual ~CSingletion(){}
static volatile T* Instance(){return m_pInstance;}
static bool CreateInstance()
{
if(!m_pInstance)
{
m_pInstance = new T;
return m_pInstance != NULL;
}
return false;
}
static bool DestroyInstance()
{
if(m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
return true;
}
return false;
}
private:
static volatile T* m_pInstance;
protocted:
CSingletion(){}
};
template<class T>
volatile T* CSingletion<T>::m_pInstance = NULL;
#endif
#include "Singleton.h"
class CTest : public CSingletion<CTest>
{
public:
CTest()
{
a = 3;
b = 4;
}
virtual ~Ctest(){}
int a;
int b;
};
int main()
{
CTest::CreateInstance();
CTest::Instance()->a = 0;
CTest::Instance()->CTest::b = 0;
std::cout<<int(CTest::Instance())<<"\t"<<int(&(CTest::Instance()->a))
<<"\t"<<int(&(CTest::Instance()->CSingletion<CTest>::Instance()->a))<<std::endl;
return 0;
}