单例模式属于创建型模式的一种,在我们进行软件开发过程中,有很多类是全局唯一只创建一次的,例如app框架类、全局管理类、配置文件、日志、数据库等,这时采用单例模式能使我们的代码变得elegant。
下面给出UML类图和C++的示例代码:

singleton

// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__

class CSingleton
{
private:
    CSingleton() {}
    ~CSingleton() {}
    static CSingleton* sm_pSingleton;

public:
    static CSingleton* Instance();
    static void ExitInstance();

public:
    void Test() {printf("CSingleton::Test()\n");}
};

#endif // __SINGLETON_H__


// singleton.cpp
#include "Singleton.h"

CSingleton* CSingleton::sm_pSingleton = NULL;

CSingleton* CSingleton::Instance()
{
    if (sm_pSingleton == NULL)
    {
        sm_pSingleton = new CSingleton;
    }
    return sm_pSingleton;
}

void CSingleton::ExitInstance()
{
    if (sm_pSingleton)
    {
        delete sm_pSingleton;
        sm_pSingleton = NULL;
    }
}

// main.cpp
#include "Singleton.h"

int main(int argc, char* argv[])
{
    CSingleton::Instance()->Test();
    CSingleton::ExitInstance();
    getchar();
    return 0;
}

此外我们可以将CSington扩展为一种模板类CSingleton<T>,避免重复去实现Instance和ExitInstance。

C/C++的宏亦可以完成精简代码的功能

#ifndef SINGLETON_H
#define SINGLETON_H

#define DISABLE_COPY(Class) \
    Class(const Class &) = delete; \
    Class &operator=(const Class &) = delete;

#define SAFE_DELETE(p) {if (p) {delete (p); (p) = NULL;}}

#define DECLARE_SINGLETON(Class) \
    public: \
        static Class* instance(); \
        static void exitInstance(); \
    private: \
        Class() {}; \
        DISABLE_COPY(Class) \
        static Class* s_pInstance;

#define IMPL_SINGLETON(Class) \
    Class* Class::s_pInstance = NULL; \
    Class* Class::instance(){ \
        if (!s_pInstance){ \
            s_pInstance = new Class; \
        } \
        return s_pInstance; \
    } \
    void Class::exitInstance(){ \
        SAFE_DELETE(s_pInstance) \
    }

#endif // SINGLETON_H

通过在一个类头文件中使用DECLARE_SINGLETON宏,实现文件中使用IMPL_SINGLETON宏,我们就将这个类定义为了一个单例类。

更多推荐