单例模式 【宏定义实现】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/amosfeng/article/details/78651628

一、代码实现

SingletonMacroDef.h

#pragma once

//单例宏定义,头文件声明
#define DECLARE_SHARE(ClassName) \
    private:\
        static ClassName* m_spInstance;\
    public:\
        static ClassName* GetInstance()\
        {\
            if(NULL == m_spInstance)\
            {\
                m_spInstance = new ClassName(); \
                static Cleaner s_clean;\
            }\
            return m_spInstance;\
        }\
    private:\
        class Cleaner\
        {\
            public:\
            Cleaner(){}\
            ~Cleaner()\
            {if( ClassName::GetInstance() ) delete ClassName::GetInstance();}\
        };\

//CPP文件静态变量声明
#define BUILD_SHARE(ClassName)\
    ClassName* ClassName::m_spInstance = NULL;

二、使用方式(示例)

  • ConfigMan.h
#pragma once
#include "SingletonMacroDef.h"

#define gConfig ConfigMan::GetInstance()

class ConfigMan
{
    DECLARE_SHARE(ConfigMan)
public:
    ConfigMan();
    ~ConfigMan();

    void Init();

}
  • ConfigMan.cpp
#include "stdafx.h"
#include "ConfigMan.h"

BUILD_SHARE(ConfigMan)

ConfigMan::ConfigMan()
{
}

ConfigMan::~ConfigMan()
{
}

void ConfigMan::Init()
{
    printf("Hello world!");
}
  • Test.cpp
#include "stdafx.h"

#include <windows.h>
#include "ConfigMan.h"

int _tmain(int argc, _TCHAR* argv[])
{
    gConfig->Init();

    system("PAUSE");
    return 0;
}

没有更多推荐了,返回首页