C++之单例模式代码实现
2017-08-24 10:54
134 查看
template <typename Type>
class Singleton
{
public:
static Type* getInstance()
{
if (!_instance)
{
unique_lock<mutex> lock(_mutex);
if (!_instance)
_instance = make_unique<Type>();
}
return _instance.get();
}
private:
static unique_ptr<Type> _instance;
static mutex _mutex;
};
#define IMPLEMENT_SINGLETON(Type) \
unique_ptr<Type> Singleton<Type>::_instance; \
mutex Singleton<Type>::_mutex;
class Singleton
{
public:
static Type* getInstance()
{
if (!_instance)
{
unique_lock<mutex> lock(_mutex);
if (!_instance)
_instance = make_unique<Type>();
}
return _instance.get();
}
private:
static unique_ptr<Type> _instance;
static mutex _mutex;
};
#define IMPLEMENT_SINGLETON(Type) \
unique_ptr<Type> Singleton<Type>::_instance; \
mutex Singleton<Type>::_mutex;
相关文章推荐
- 《大话设计模式》读书笔记(C++代码实现) 第一章:简单工厂模式
- 《大话设计模式》读书笔记(C++代码实现) 第二章:策略模式
- 《大话设计模式》读书笔记(C++代码实现) 第六章:装饰模式
- 生成器模式及C++代码实现
- 《大话设计模式》读书笔记(C++代码实现) 第七章:代理模式
- C++之设计模式实现代码
- 设计模式C++实现——观察者模式 (及附带Cocos2d观察者模式代码)
- 观察者模式的c++代码实现
- 单例模式及C++实现代码
- 代理模式c++代码的实现
- 模板模式c++代码实现
- Singleton模式的C++实现研究(示例代码)
- 装饰模式c++代码实现
- 原型模式及C++代码实现
- 《Head First设计模式》之装饰者模式实例代码C++实现
- 《大话设计模式》读书笔记(C++代码实现) 第一章:简单工厂模式
- Singleton模式的C++实现研究(示例代码)
- Singleton模式的C++实现研究(示例代码)
- 装饰者模式及C++代码实现
- 《大话设计模式》读书笔记(C++代码实现) 第六章:装饰模式