// 使用SingletonT可以确保使用SingletonT获得的相同类的对像是唯一的。
#pragma once
#ifndef _SINGLETONT_H_
#define _SINGLETONT_H_
template
class SingletonT
{
protected:
SingletonT(void);
public:
virtual ~SingletonT(void);
public:
static T* Instance();
private:
static T* _instance;
};
#ifdef _DEBUG
#include
using namespace std;
#endif // _DEBUG
template
T* SingletonT
::_instance = 0;
template
SingletonT
::SingletonT(void) { #ifdef _DEBUG cout<<"SingletonT"<
SingletonT
::~SingletonT(void) { #ifdef _DEBUG cout<<"~SingletonT"<
T* SingletonT
::Instance() { if (_instance == 0) { #ifdef _DEBUG cout<<"Instance T"<
class SingletonT { public: SingletonT(){} ~SingletonT(){} static T* GetInstance() { static T t; return &t; } private: enum{ value = v}; }; #ifndef __SINGLETONSAFET_H__ #define __SINGLETONSAFET_H__ #include
#include
/ // 工程: // 作者: // 描述: // 主要函数: // 日期: // 版本: 1.0 // 修改: / class CLocker { public: CLocker() { InitializeCriticalSection(&m_cs); } ~CLocker() { DeleteCriticalSection(&m_cs); } void Lock() { EnterCriticalSection(&m_cs); } void UnLock() { LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION m_cs; }; / // 工程: // 作者: // 描述: 单例模版类 // 主要函数: // 日期: // 版本: 1.0 // 修改: / template
class SingletonSafeT { public: static T* GetInstance() { if (__instance == NULL) { Lock.Lock(); if (__instance == NULL) { __instance = new T(); } Lock.UnLock(); } return __instance; } SingletonSafeT(){}; ~SingletonSafeT(){ Release(); }; private: static T* __instance; static CLocker Lock; static void Release() { if (__instance != NULL) { Lock.Lock(); if (__instance != NULL) { delete __instance; __instance = NULL; } Lock.UnLock(); } } }; template
T* SingletonSafeT
::__instance = NULL; template
CLocker SingletonSafeT
::Lock; #endif // __SINGLETONSAFET_H__