1.懒汉式(多线程不安全) - 需要时才进行实例化。
#include<iostream>
using namespace std;
#include <windows.h>
//核心的本质就是,只能实例化一个实体
class Singleton {
private:
Singleton() {}
Singleton(Singleton&) = delete; //禁止使用
Singleton& operator=(const Singleton&object) = delete; //禁止使用
public:
~Singleton() {}
//获取一个实例
static Singleton* getInstance() {
//如果指针为空,则重新创造一个实例
if (m_instance_ptr == nullptr) {
m_instance_ptr = new Singleton;
}
//否则,说明已经创建过了,直接返回
return m_instance_ptr;
}
void func()
{
cout << "成功实例化了!!!" << endl;
}
private:
static Singleton* m_instance_ptr;
};
Singleton* Singleton::m_instance_ptr = nullptr;//在外部对指针进行初始化
int main() {
static Singleton* instance = Singleton::getInstance();
instance->func();
system("pause");
return 0;
}
2.懒汉式(多线程安全)-进行加锁
#include <iostream>
#include <memory> // shared_ptr
#include <mutex> // mutex
class Singleton {
public:
typedef std::shared_ptr<Singleton> Ptr;
~Singleton() {
std::cout << "析构函数!!!" << std::endl;
}
Singleton(Singleton&) = delete; //禁止使用
Singleton& operator=(const Singleton&) = delete; //禁止使用
static Ptr getInstance() {
if (m_instance_ptr == nullptr) {
std::lock_guard<std::mutex> auto_lock(m_mutex);
if (m_instance_ptr == nullptr) {
m_instance_ptr = std::shared_ptr<Singleton>(new Singleton);
}
}
return m_instance_ptr;
}
void use() const {
std::cout << "已经成功初始化了" << std::endl;
}
private:
Singleton() {}
static Ptr m_instance_ptr;
static std::mutex m_mutex;
};
Singleton::Ptr Singleton::m_instance_ptr = nullptr;
std::mutex Singleton::m_mutex;
int main() {
Singleton::Ptr instance = Singleton::getInstance();
instance->use();
system("pause");
return 0;
}
3.饿汉式-提前实例化
#include <iostream>
class Singleton {
public:
~Singleton() {
std::cout << "析构函数!!!" << std::endl;
}
Singleton(Singleton&) = delete; //禁止使用
Singleton& operator=(const Singleton&) = delete; //禁止使用
static Singleton* getInstance() {
return m_instance;
}
void use() const {
std::cout << "已经实例化对象了!!!" << std::endl;
}
private:
Singleton() {}
static Singleton* m_instance;
};
//直接在外部就只实例化一个对象,避免的多创建的风险
Singleton* Singleton::m_instance = new Singleton;
int main() {
Singleton* instance = Singleton::getInstance();
instance->use();
system("pause");
return 0;
}