// singleton.cpp
#include <stdio.h>
#ifdef _X_RELEASE_
#define TRACE(str)
#else
#define TRACE(str) printf("%s/n", str)
#endif
class CSingleton
{
private:
static CSingleton* m_pUniqueInstance;
public:
static CSingleton* Instance();
protected:
CSingleton()
{
TRACE("CSingleton");
}
public:
virtual ~CSingleton()
{
TRACE("~CSingleton");
}
void SingletonOperation();
};
CSingleton* CSingleton::m_pUniqueInstance = 0;
CSingleton* CSingleton::Instance()
{
TRACE("Instance");
if (0 == m_pUniqueInstance)
{
m_pUniqueInstance = new CSingleton();
}
return m_pUniqueInstance;
}
void CSingleton::SingletonOperation()
{
TRACE("SingletonOperation");
}
int main()
{
CSingleton* pSingleton = CSingleton::Instance();
if (!pSingleton)
{
TRACE("error 1");
return 1;
}
pSingleton->SingletonOperation();
delete pSingleton;
pSingleton = 0;
return 0;
}
/*
root@ubuntu:/home/hgc/test# g++ singleton.cpp -o singleton -g -Wall
root@ubuntu:/home/hgc/test# ./singleton
Instance
CSingleton
SingletonOperation
~CSingleton
root@ubuntu:/home/hgc/test#
*/
// singleton_template.cpp
#include <stdio.h>
#ifdef _X_RELEASE_
#define TRACE(str)
#else
#define TRACE(str) printf("%s/n", str)
#endif
// 单件类模板
template <typename TSingletonData>
class CSingleton
{
private:
static CSingleton<TSingletonData>* m_pUniqueInstance;
TSingletonData m_SingletonData;
public:
static CSingleton<TSingletonData>* Instance();
TSingletonData& GetSingletonData();
protected:
CSingleton()
{
TRACE("CSingleton");
}
public:
virtual ~CSingleton()
{
TRACE("~CSingleton");
}
};
template <typename TSingletonData>
CSingleton<TSingletonData>* CSingleton<TSingletonData>::m_pUniqueInstance = 0;
template <typename TSingletonData>
CSingleton<TSingletonData>* CSingleton<TSingletonData>::Instance()
{
TRACE("Instance");
if (0 == m_pUniqueInstance)
{
m_pUniqueInstance = new CSingleton();
}
return m_pUniqueInstance;
}
template <typename TSingletonData>
TSingletonData& CSingleton<TSingletonData>::GetSingletonData()
{
return m_SingletonData;
}
// 需要在系统中具有唯一实例的类
class CSingletonData
{
friend class CSingleton<CSingletonData>; // 友元类
private:
// 私有的构造函数,只能被友元类访问
CSingletonData()
{
TRACE("CSingletonData");
}
public:
virtual ~CSingletonData()
{
TRACE("~CSingletonData");
}
void Operation()
{
TRACE("Operation");
}
};
// 通过单件模板类访问CSingletonData类的唯一实例
#define CSingletonDataInstance CSingleton<CSingletonData>::Instance()
int main()
{
if (!CSingletonDataInstance)
{
TRACE("error 1");
return 1;
}
CSingletonDataInstance->GetSingletonData().Operation();
delete CSingletonDataInstance;
return 0;
}
/*
root@ubuntu:/home/hgc/test# g++ singleton_template.cpp -o singleton_template -g -Wall
root@ubuntu:/home/hgc/test# ./singleton_template
Instance
CSingletonData
CSingleton
Instance
Operation
Instance
~CSingleton
~CSingletonData
root@ubuntu:/home/hgc/test#
*/