目的
设计单例模式的目的是为了解决两个问题:
- 保证一个类只有一个实例
这种需求是需要控制某些资源的共享权限,比如文件资源、数据库资源。
- 为该实例提供一个全局访问节点
相较于通过全局变量保存重要的共享对象,通过一个封装的类对象,通过提供全局访问节点,不仅可以保护全局对象不被覆盖,同时能够将分散的代码封装在一个类中。
实现方式
- 将默认构造函数设为私有,防止其他对象使用单例的new运算符;
- 新建静态构造方法作为构造单例对象的构造方法,该方法调用私有构造函数创建单例对象并保存在一个静态变量中,后续所有对该静态方法的调用都会返回该缓存对象。
具体的实现方式又分为饿汉模式和懒汉模式。饿汉模式即在初始阶段就主动进行实例化,即存储单例对象的静态变量在初始化阶段即通过new运算符构建一个单例对象,无论该单例是否有人使用;懒汉模式即在静态构造方法中构造单例对象,且只有在单例对象为空(nullptr)时才会主动构建对象。
但懒汉模式在多线程情况下其实是有缺陷的,如果并发请求,同时调用静态构造方法,则存储单例对象的静态变量会被多次复制,违背的单例的理念。这种情况下用锁来保证同步。但是同步锁使用不当不仅会带来不必要的风险,同时加锁、解锁也是对资源的浪费,因此饿汉模式反倒是一种更好的方式,如果单例迟早要被实例化,那么延迟加载的意义就不大。懒汉模式实现代码如下:
class Singleton
{
private:
static Singleton* pinstance_;
static std::mutex mutex_;
protected:
Singleton(const std::string value) : value_(value)
{
}
~Singleton() {}
std::string value_;
public:
Singleton(Singleton& other) = delete;
void operator=(const Singleton&) = delete;
static Singleton* GetInstance(const std::string& value);
std::string value() const {
return value_;
}
};
Singleton* Singleton::pinstance_{ nullptr };
std::mutex Singleton::mutex_;
Singleton* Singleton::GetInstance(const std::string& value)
{
if (pinstance_ == nullptr){
std::lock_guard<std::mutex> lock(mutex_);
if (pinstance_ == nullptr)
{
pinstance_ = new Singleton(value);
}
return pinstance_;
}
}
void ThreadFoo() {
// Following code emulates slow initialization.
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar() {
// Following code emulates slow initialization.
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout << "If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
return 0;
}