设计模式-单例模式

目的:为了保证一个类在程序中只有一个实例,并且能被全局访问

场景:全局线程池

要点:

通过 Test::Instance()获取类指针

class Test
{
public:
    static Test* Instance()
    {
        if (m_instance == nullptr)
        {
            std::lock_guard lock(m_mutex);
            if (m_instance == nullptr)
                m_instance = new Test;
        }
        return m_instance;
    }

    static void DeleteInstance()
    {
        if (m_instance)
        {
            std::lock_guard lock(m_mutex);
            if (m_instance)
            {
                delete m_instance;
                m_instance = nullptr;
            }
        }
    }

private:
    Test() {}

private:
    static Test *m_instance;
    static std::mutex m_mutex;
};

Test* Test::m_instance = NULL;
std::mutex Test::m_mutex;

每个类想要实现单例模式,都要写一遍 Instance的接口,有点麻烦,于是希望能用宏实现单例模式,最终使用效果为:

class Test
{
    SINGELTON(Test)
private:
    Test() {}
};

可以用类模板的方式来进行:

template
class Singleton
{

public:
    static T *Instance()
    {
        if (m_instance == nullptr)
        {
            std::lock_guard lock(m_instanceMutex);
            if (m_instance == nullptr)
                m_instance = std::unique_ptr(new T);
        }
        return m_instance.get();
    }

private:
    static std::unique_ptr m_instance;
    static std::mutex m_instanceMutex;
};

template std::mutex Singleton::m_instanceMutex;
template std::unique_ptr Singleton::m_instance(nullptr);

//单例宏
#define SINGELTON(OBJ_CLASS)                            \
    friend Singleton;                        \
                                                        \
public:                                                 \
    static OBJ_CLASS *Instance()                        \
    {                                                   \
        return Singleton::Instance();        \
    }

Original: https://www.cnblogs.com/yaronzz/p/16351984.html
Author: Yaronzz
Title: 设计模式-单例模式

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/585295/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球