1.想要实现一个单例设计模式,必须遵循以下规则:
- 私有的构造函数:防止外部代码直接创建类的实例
- 私有的静态实例变量:保存该类的唯一实例
- 公有的静态方法:通过公有的静态方法来获取类的实例
2.单例模式主要分为饿汉式和懒汉式:
饿汉式:在类被加载时就会创建该类的实例对象。
懒汉式:在类被加载时不回创建该类的实例对象,在首次要使用该实例时才会创建。
3.C++代码如下:
#include <iostream>
using std::cout;
using std::endl;
//懒汉式
class SingletonLazy{
public:
static SingletonLazy& getinstance(){
static SingletonLazy m_instance;
return m_instance;
}
public:
SingletonLazy(const SingletonLazy&) = delete;//禁止拷贝构造函数的调用
SingletonLazy(SingletonLazy&&) = delete;//禁止移动构造函数的调用
SingletonLazy& operator=(const SingletonLazy&) = delete;//禁止拷贝赋值操作符的调用
SingletonLazy& operator=(SingletonLazy&&) = delete;//禁止移动赋值操作符的调用
private:
SingletonLazy(){
cout<<"ConstructorLazy called"<<endl;
}
~SingletonLazy(){
cout<<"DestructorLazy called"<<endl;
}
};
//饿汉式
class SingletonHungry{
public:
static SingletonHungry& getinstance(){
return m_instance;
}
public:
SingletonHungry(const SingletonHungry&) = delete;
SingletonHungry(SingletonHungry&&) = delete;
SingletonHungry& operator=(const SingletonHungry&) = delete;
SingletonHungry& operator=(SingletonHungry&&) = delete;
private:
static SingletonHungry m_instance;
SingletonHungry(){
cout<<"ConstructorHungry called"<<endl;
}
~SingletonHungry(){
cout<<"DestructorHungry called"<<endl;
}
};
SingletonHungry SingletonHungry::m_instance;
int main(){
SingletonLazy& instance_1=SingletonLazy::getinstance();
SingletonHungry& instance_2=SingletonHungry::getinstance();
return 0;
}
4.代码解释:
由于在main函数之前初始化,所以没有线程安全的问题。但是潜在问题在于no-local static对象(函数外的static对象)在不同编译单元中的初始化顺序是未定义的。也即,static Singleton m_instance;和static Singleton& getInstance()⼆者的初始化顺序不确定,如果在初始化完成之前调⽤ getInstance() ⽅法会返回⼀个未定义的实例。
这是最推荐的一种单例实现方式:
1.静态内部类的特性完全符合懒汉式单例模式的特点,在加载外部类时不会创建静态内部类,在静态内部类中的属性被调用时才会创建,如果静态内部类的属性被static修饰,只会实例化一次。
2.通过局部静态变量的特性保证了线程安全,不需要使用共享指针,代码简洁,不需要使用互斥锁,没有双重检查锁定模式的风险。
3.注意在使用的时候需要声明单例的引用 SingletonPattern_V3& 才能获取对象。
运行结果:
ConstructorHungry called
ConstructorLazy called
DestructorLazy called
DestructorHungry called
分析运行结果:
1.ConstructorHungry called:饿汉式单例在类加载时初始化。
2.ConstructorLazy called:懒汉式单例在第一次调用 getinstance() 时初始化。
3.DestructorLazy called 和 DestructorHungry called:析构函数按照与构造函数相反的顺序被调用。