#include "stdafx.h"
#include <iostream>
using namespace std;
#define SAFE_DELETE(ptr) if(ptr){delete (ptr); (ptr) = NULL;}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//动态的
template< class TChild >
class SingletonDynamic
{
public:
static TChild* instance()
{
return GetInstance();
}
static void Release()
{
// 可以取到
TChild* &pChild = GetInstanceObj();
// 释放
SAFE_DELETE( pChild );
// 设置释放成功
SetReleased();
}
protected:
static TChild* GetInstance()
{
if( IsReleased() ) return NULL;
return GetInstanceObj();
}
static TChild*& GetInstanceObj()
{
// 相当于成员变量
static TChild* s_pChild = NULL;
if( NULL == s_pChild )
s_pChild = new TChild();
return s_pChild;
}
static bool IsReleased()
{
return GetReleaseObj();
}
static void SetReleased()
{
bool &IsReleased = GetReleaseObj();
IsReleased = true;
}
static bool& GetReleaseObj()
{
// 相当于成员变量
static bool IsReleased = false;
return IsReleased;
}
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
@brief 静态单例
@remarks 可优化
*/
template< class TChild >
class SingletonStatic
{
public:
static TChild* instance()
{
static TChild s_Child;
return &s_Child;
}
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//接口可配置单例
template< class Type >
class SingletonConfigurable
{
public:
static bool Available();
static Type * GetInstance();
protected:
void install();
void uninstall();
private:
static Type * m_pInstance;
};
template< class Type >
Type *SingletonConfigurable<Type>::m_pInstance = NULL;
template< class Type >
inline bool SingletonConfigurable<Type>::Available()
{
if ( m_pInstance != NULL )
{
return TRUE;
}
return FALSE;
}
template< class Type >
inline Type *SingletonConfigurable<Type>::GetInstance()
{
assert( m_pInstance != NULL );
return m_pInstance;
}
template< class Type >
inline void SingletonConfigurable<Type>::install()
{
assert( m_pInstance == NULL );
m_pInstance = static_cast<Type *>( this );
}
template< class Type >
inline void SingletonConfigurable<Type>::uninstall()
{
assert( m_pInstance != NULL );
m_pInstance = NULL;
}
//全局变量
int gCount = 0;
//测试类
class Test
{
public:
Test()
{
gCount++;
}
void OutPut()
{
cout << gCount << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test *pTest = SingletonStatic<Test>::instance();
Test *pTest2 = SingletonStatic<Test>::instance();
pTest->OutPut();
return 0;
}