定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。
UML结构图
单例看似简单,但是涉及多种实现方式。
分类:
懒汉实现:顾名思义,无论是否使用,先创建了再说
饿汉方式:使用时创建
如何实现线程安全的单例模式呢?
由于C++11及以后的版本中,静态变量初始化是线程安全。上代码:
class Singleton{
public:
static Singleton& getInstance(){
static Singleton m_instance; //局部静态变量
return m_instance;
}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
protected:
Singleton() = default;
~Singleton() = default;
};
备注:
拷贝构造函数和赋值构造函数设置为delete。避免对象被再次构造或者拷贝。
利用模板实现单例:
template<typename T>
class Singleton
{
public:
static T& getInstance() {
static T t;
return t;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
protected:
Singleton() = default;
~Singleton() = default;
};
模板单例使用:
class MySingleon:public Singleton
{
public:
void myTest()
{
std::cout<<“mySingleton”<<std::endl;
}
};
int main()
{
MySingleon::getInstance().myTest();
return 0;
}
另一种简单使用方法:
class MySingleon
{
public:
void myTest()
{
std::cout<<“MySingleon”<<std::endl;
}
};
int main()
{
Singleton<MySingleon>::getInstance().myTest();
return 0;
}