#ifndef TEMPLATE_SINGLETON_H
#define TEMPLATE_SINGLETON_H

#include <mutex>

// 定义单例(声明友元)
#define SINGLETON_DEFINE(Class, ...) \
    friend TemplateSingleton<Class, ##__VA_ARGS__>;

// 创建单例(不存在创建，存在获取本类唯一单例)
#define SINGLETON_CREATE(Class, ...) \
    TemplateSingleton<Class, ##__VA_ARGS__>::CreateInstance

// 销毁单例
#define SINGLETON_DELETE(Class, ...) \
    TemplateSingleton<Class, ##__VA_ARGS__>::DeleteInstance


template <typename Class, typename ...Args>
class TemplateSingleton
{
public:
    static Class* CreateInstance(Args ...args);
    static void DeleteInstance();

private:
    static Class* s_pObject;
    static std::mutex s_mutex;
};

template <typename Class, typename ...Args>
Class* TemplateSingleton<Class, Args...>::CreateInstance(Args ...args)
{
    if (s_pObject == nullptr)
    {
        std::lock_guard<std::mutex> unique(s_mutex);
        if (s_pObject == nullptr)
        {
            s_pObject = new Class(args...);
        }
    }
    return s_pObject;
}

template <typename Class, typename ...Args>
void TemplateSingleton<Class, Args...>::DeleteInstance()
{
    if (s_pObject != nullptr)
    {
        std::lock_guard<std::mutex> unique(s_mutex);
        if (s_pObject != nullptr)
        {
            delete s_pObject;
            s_pObject = nullptr;
        }
    }
}

template <typename Class, typename ...Args>
Class* TemplateSingleton<Class, Args...>::s_pObject = nullptr;

template <typename Class, typename ...Args>
std::mutex TemplateSingleton<Class, Args...>::s_mutex;

#endif //TEMPLATE_SINGLETON_H
