对于单例设计模式做一个简单的记录。
使用场景:如果一个类在整个程序的运行环境中,有且仅需一个实例,可以使用单例设计模式。
Singleton模式主要设计思路就是用private 或 protected 修饰构造函数,并在全局维护唯一的实例,通过接口向外部提供这个实例。
下面是简单的代码实现。
// Singleton.h
class Singleton
{
public:
Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};
//Singleton.cpp
Singleton* Singleton::_instance = nullptr;
Singleton::Singleton()
{
}
Singleton* Single::Instance()
{
if(_instance == nullptr)
{
_instance = new Singleton();
}
return _instance;
}
上面的代码简单的实现了单例设计模式,但是却不是线程安全的,多个线程同时运行到
if(_instance == nullptr)
会创建多个Singleton对象。
解决的方法很多,比如加锁,这里提供一个最简单的方法:就是著名的饿汉式,用空间换安全。
//Singleton.h
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
}
//Singleton.cpp
Singleton* Singleton::_instance = new Singleton();
Singleton* Singleton::Instance()
{
return _instance;
}