#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)
C++单例模式demo
于 2022-10-11 15:06:41 首次发布