单例模式之类模板实现

/*
* Copyright (c) 2018,Fzuim
* All rights reserved.
*
* 文件名称:SingletonObj.h
* 摘 要:  单例模式,使用类模板
* 用法示例  DECLARE_SINGLETON(CDestObject);
*
* 当前版本:1.0
* 作 者:  Fzuim
* 完成日期:2018年3月8日
*/

#pragma once

template<class TYPE>
class CSingletonObj
{
public:
    CSingletonObj(){};
    ~CSingletonObj(){};

    static TYPE* GetInstance()
    {
        try
        {
            if (NULL == m_pInstance)
            {
                m_pInstance = new TYPE;
            }
        }
        catch(...)
        {

        }
        return m_pInstance;
    }

    static void Release()
    {
        if (NULL != m_pInstance)
        {
            delete m_pInstance;
            m_pInstance = NULL;
        }
    }
private:
    static TYPE* m_pInstance;
};

/*
 *  在类外定义成员函数,若此成员函数中有模板参数存在,则除了需要和一般类的类外定义成员函数一样的定义外,
 *  还需要在函数外进行模板声明 template<class T>
 */
template<class TYPE>
TYPE* CSingletonObj<TYPE>::m_pInstance = NULL;

/*
 *  这边比较难理解的就是:为什么要声明友元类?
 *  在于CSingletonObj<Obj>::GetInstance()需要去new Obj要访问到构造函数,如果构造函数是private则访问不了,
 *  声明为友元,可以完全访问
 */
#define DECLARE_SINGLETON(Obj) \
friend class CSingletonObj<Obj>; \
public: \
static Obj *GetInstance() \
{ \
return CSingletonObj<Obj>::GetInstance(); \
} \
static void Release() \
{ \
CSingletonObj<Obj>::Release();  \
}

/*
 *  类使用栗子
 */
class CTestObj
{
    DECLARE_SINGLETON(CTestObj);
private:
    CTestObj(){};
    ~CTestObj(){};
public:
    void DoTest()
    {
        printf("Test...\n");
    };
};

调用栗子:

#include "stdafx.h"
#include "SingletonObj.h"

int _tmain(int argc, _TCHAR* argv[])
{
    CTestObj* pObj = CTestObj::GetInstance();
    pObj->DoTest();
    pObj->Release();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fzuim/article/details/79483165