懒汉模式
class Singleton{
public:
static Singleton& getInstance(){
if(m_pIntance == nullptr){
m_mutex.lock(); // 互斥锁,保证多线程中也是单例的。
if(m_pIntance == nullptr){
m_pIntance = new Singleton();
}
m_mutex.unlock();
}
return m_pInstance;
}
void fuck(){
cout << "fuck something" << endl;
}
private:
Singleton *m_pIntance;
std::mutex m_mutex;
Singleton() = delete; //阻止外部构造
Singleton(Singleton const &singleton) = delete; //阻止拷贝构造
Singleton& operator=(Singleton const &singleton) = delete; //阻止拷贝赋值
};
main()
{
Singleton::getInstance().fuck();
}
饿汉模式
class Singleton{
public:
static Singleton& getInstance(){
static Singleton instance; //在程序启动时就加载,线程安全。
return instance;
}
void fuck(){
cout << "fuck something" << endl;
}
private:
Singleton() = delete; //阻止外部构造
Singleton(Singleton const &singleton) = delete; //阻止拷贝构造
Singleton& operator=(Singleton const &singleton) = delete; //阻止拷贝赋值
};
main()
{
Singleton::getInstance().fuck();
}