设计模式之单例模式

/*
1.单例模式的类只提供私有的构造函数
2.类定义中含有一个该类的静态私有对象
3.该类提供了一个静态的公有的函数用于创建它本身的静态私有对象
*/
class Singleton
{
public:
	static Singleton* GetInstance()
	{
		if(pInstance == nullptr)//懒加载,只有在使用时才生成
		{
			pthread_mutex_lock(&mutex);//多线程竞争的安全问题
			if(pInstance == nullptr)//单线程提高获取释放锁的效率
			{
				pInstance = new Singleton();
			}
			pthread_mutex_lock(&mutex);
		}
		return pInstance;
	}
	static void release()
	{
		if(pInstance != nullptr)
		{
			delete pInstance;
			pInstance = nullptr;
		}
	}
private:
	Singleton(){}
	static Singleton* pInstance;
};
Singleton* Singleton:: pInstance = nullptr;

 

你可能感兴趣的:(设计模式,单例模式,设计模式)