C++单例模式demo

#pragma once

#include <memory>

namespace util {
    
    
 template < class type >
    class Singleton
    {
    
    
    public:
        Singleton(){
    
    }
        ~Singleton(){
    
    }

        inline static type & getSingleton()
        {
    
    
            if (!_singleton)
            {
    
    
                _singleton = new type();
            }
            return *_singleton;
        }
        inline static type * getSingletonPtr()
        {
    
    
            if (!_singleton)
            {
    
    
                _singleton = new type();
            }
            return _singleton;
        }
    protected:
        static type* _singleton;
    };

    template < class type >
    type* Singleton<type>::_singleton = nullptr;


    //first param
    template < class type, class param >
    class SingletonFirst
    {
    
    
    public:
        SingletonFirst(){
    
    }
        ~SingletonFirst(){
    
    }

        inline static type & getSingleton()
        {
    
    
            if (!_singleton)
            {
    
    
                _singleton = new type(new param());
            }
            return *_singleton;
        }
        inline static type * getSingletonPtr()
        {
    
    
            if (!_singleton)
            {
    
    
                _singleton = new type(new param());
            }
            return _singleton;
        }
    protected:
        static type* _singleton;
    };

    template < class type, class param>
    type* SingletonFirst<type, param>::_singleton = nullptr;
};


//用法,我在自己的日志类中使用过这个单例模式
//具体为
typedef util::Singleton<LoggerManager> LoggerMgr;
//宏定义时
#define LOG(name) coke::LoggerMgr::getSingletonPtr()->getLogger(name)

猜你喜欢

转载自blog.csdn.net/weixin_46324584/article/details/127263939