//******************************* 懒汉式1 *******************************
#include <iostream>
#include <memory> // shared_ptr
#include <mutex> // mutex
// version 2: thread is safe now and memory doesn't leak
class Singleton
{
public:
typedef std::shared_ptr<Singleton> Ptr;
~Singleton()
{
std::cout << "destructor called!" << std::endl;
}
Singleton(Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Ptr get_instance()
{
//注意这里双重判断
if (m_instance_ptr == nullptr)
{
std::lock_guard<std::mutex> lk(m_mutex);//C++11加互斥锁,可以自动解锁
if (m_instance_ptr == nullptr)
{
m_instance_ptr = std::shared_ptr<Singleton>(new Singleton);
}
}
return m_instance_ptr;
}
private:
Singleton()
{
std::cout << "constructor called!" << std::endl;
}
static Ptr m_instance_ptr;
static std::mutex m_mutex;
};
// initialization static variables out of class
Singleton::Ptr Singleton::m_instance_ptr = nullptr;
std::mutex Singleton::m_mutex;
int main()
{
Singleton::Ptr instance1 = Singleton::get_instance();
Singleton::Ptr instance2 = Singleton::get_instance();
return 0;
}
//******************************* 懒汉式2 *******************************
//懒汉式在不使用锁机制的情况下保证线程安全
#include <iostream>
class Singleton1{
public:
~Singleton1()
{
std::cout << "destructor called!" << std::endl;
}
Singleton1(const Singleton1&) = delete;
Singleton1& operator=(const Singleton1&) = delete;
static Singleton1& get_instance()
{
static Singleton1 instance;
return instance;
}
private:
Singleton1()
{
std::cout << "constructor called!" << std::endl;
}
};
int main(int argc, char* argv[])
{
Singleton1& instance_1 = Singleton1::get_instance();
Singleton1& instance_2 = Singleton1::get_instance();
return 0;
}
//******************************* 饿汉式1 *******************************
//全局的单例实例在类装载时构建。
#include <iostream>
using namespace std;
class Singleton2{
private:
static Singleton2* pInstance;
Singleton2()
{
cout << "constructor called!" << std::endl;
}
Singleton2(const Singleton2&) = delete;
Singleton2& operator = (const Singleton2&) = delete;
public:
static Singleton2* getInstance();
~Singleton2()
{
std::cout << "destructor called!" << std::endl;
}
void print()
{
cout << "this = " << this << endl;
}
};
Singleton2* Singleton2::pInstance = new Singleton2; //的单例实例在类装载时构建。
// 静态方法返回该实例
Singleton2* Singleton2::getInstance()
{
return pInstance;
}
int main()
{
Singleton2* s1 = Singleton2::getInstance();
Singleton2* s2 = Singleton2::getInstance();
s1->print();
s2->print();
return 0;
}
设计模式 —— 单例模式
最新推荐文章于 2024-04-26 16:22:39 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)