C++单例模式

18 阅读1分钟

单例模式介绍

什么是单例模式

单例模式是指在整个系统生命周期内,保证一个类只能产生一个实例,确保该类的唯一性。

为什么需要单例模式

  1. 节省资源。一个类只有一个实例,不存在多份实例,节省资源。
  2. 方便控制。在一些操作公共资源的场景时,避免了多个对象引起的复杂操作。

懒汉式和饿汉式单例模式的实现

线程安全的懒汉模式

由于懒汉式是只有当需要使用该实例时,才会去创建并使用实例。因此这种方式要考虑线程安全。要实现线程安全,就要给每次创建实例的代码部分加上互斥锁

#include <iostream>
#include <mutex>
using namespace std;
// 线程安全懒汉式
template <typename T>
class Singleton
{
public:
	static T* getInstance()
	{
		if(instance_ == nullptr)
		{
			mutex_.lock();
			if (instance_ == nullptr)
			{
				instance_ = new T();
			}
			mutex_.unlock();
		}
		return instance_;
	}
private:
	Singleton() = delete;
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;

private:
	static T* instance_;
	static mutex mutex_;
};

// 静态成员变量的外部初始化
template <typename T>
T* Singleton<T>::instance_ = nullptr;

template <typename T>
mutex Singleton<T>::mutex_;  // 初始化静态互斥锁

class Printer
{
	friend class Singleton<Printer>;

private:
	Printer() = default;
	Printer(const Printer&) = delete;
	Printer& operator=(const Printer&) = delete;

public:
	void print() {
		cout << "Printer" << endl;
	}
};

int main()
{
	Singleton<Printer>::getInstance()->print();
}

饿汉模式

饿汉式单例模式没有线程安全问题

#include <iostream>

using namespace std;

// 饿汉模式
template <typename T>
class Singleton
{
private:
	Singleton() = delete;
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;

public:
	static T* getInstance()
	{
		return instance_;
	}
private:
	static T* instance_;
};

template <typename T>
T* Singleton<T>::instance_ = new T();

class Printer
{
	friend class Singleton<Printer>;

private:
	Printer() = default;
	Printer(const Printer&) = delete;
	Printer& operator=(const Printer&) = delete;

public:
	void print() {
		cout << "Printer" << endl;
	}
};

int main() {
	Singleton<Printer>::getInstance()->print();
}