/////////////////////////////////
//singleton template file
//SingleEx.h
#ifndef SINGLETONEX__H__
#define SINGLETONEX__H__
//File Name : SingletonEx.h
//作用 : 提供单件模板功能(singleton template)
//Copyright(C) C++
//Microsoft Visual C++ 6.0 , GCC Ver2.95.3-6 编译通过
//作者:古斌亮
//时间:2002.12.25
//EMail : [email protected]
template<class T>
class CSingletonBase
{
protected:
inline static T* Create(void)
{
if(m_pt==NULL)
{
m_pt=new T();
}
return m_pt;
}
inline static void Free(void)
{
delete m_pt;
m_pt=NULL;
}
protected:
CSingletonBase()
{
}
virtual ~CSingletonBase()
{
delete m_pt;
}
private:
CSingletonBase(const CSingletonBase& sig)
{
}
CSingletonBase& operator = (const CSingletonBase& sig)
{
}
private:
static T * m_pt;
};
template<class T>
T* CSingletonBase<T>::m_pt = NULL;
template<class T>
class CSingletonEx : private CSingletonBase<T>
{
public:
CSingletonEx()
{
}
virtual ~CSingletonEx()
{
}
public:
virtual T* Instance(void)
{
return CSingletonBase<T>::Create();
}
virtual void Release(void)
{
CSingletonBase<T>::Free();
}
private:
CSingletonEx(const CSingletonEx& sig)
{
}
CSingletonEx& operator = (const CSingletonEx& sig)
{
}
};
#endif //SINGLETONEX__H__
////////////////////////////////
//测试类
//Doc.h
#ifndef CDOC__H__
#define CDOC__H__
class CDoc //测试类
{
public:
CDoc(const std::string name = "NoName"):m_name(name){}
virtual ~CDoc(){}
public:
inline
std::string Name()
{
return m_name;
}
inline
void SetName(const std::string& name)
{
m_name=name;
}
protected:
std::string m_name;
};
#endif //CDOC__H__
////////////////////////////////////
//测试文件
//main.cpp
#include<iostream>
#include<string>
#include "singletonex.h"
#include "doc.h"
void TestSingletonEx(void)
{
CSingletonEx<CDoc> s;
CDoc *pdoc = s.Instance();
std::cout<<pdoc->Name()<<std::endl;
pdoc->SetName("pdoc change: My SingletonEx");
CDoc *p2 = s.Instance();
std::cout<<p2->Name()<<std::endl;
p2->SetName("p2 change: SingletonEx ");
std::cout<<pdoc->Name()<<std::endl;
}
void main(void)
{
std::cout<<"******** Test SingletonEx Start ******** "<<std::endl;
TestSingletonEx();
}
//the end!!