什么是单例模式?
The singleton design pattern ensures that a class has only one instance and provides a global point of access to that intance.
Encapsulated “just-in-time initialization" or “initialization on first use” or “lazy intialization”
应用场景
-Say each country can have only one president.
-configuration manager
-database manager
如何实现?
- make the constructor private
- create a private static variable named instance
- create a public static method as a global point of access to the instance.
C++ 代码实现
Singleton.h
class Singleton{
private:
int data;
static Singleton* instance;
Singleton(int v = 0){ data = v;};
public:
void setData(int val);
int getData();
static Singleton* getInstance();
};
Singleton.cpp
Singleton::instance = nullptr; //懒汉模式
//Singleton::instance = new Singleton(); //饿汉模式
void Singleton::setData(int val)
{
data = val;
}
int Singleton::getData()
{
return data;
}
Singleton* Singleton::getInstance()
{
if(instance == nullptr)
instance = new Singleton();//lazy intialization
return instance;
}
main.cpp
int main()
{
Singleton* singleton = Singleton::getInstance();
}
懒汉模式 vs 饿汉模式
懒汉模式: 效率高, but not thread safe(需要加锁)
饿汉模式: 效率低, but thread safe
Thread-safe Singleton with C++ 11 using Magic Statics
在C++11内部静态变量的方式里是线程安全的
class CSingleton final
{
public:
static CSingleton& GetInstance();
private:
CSingleton() = default;
~CSingleton() = default;
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
CSingleton(CSingleton&&) = delete;
CSingleton& operator=(CSingleton&&) = delete;
};
CSingleton& CSingleton::GetInstance()
{
static CSingleton instance;
return instance;
}
缺点(反模式)
Singleton is also considered as an “Anti-Pattern”.
- Singleton doesn’t support object-oriented design principles. It cannot be inherited. No control over creation. Prevents dependency injection.
- Singleton do not allow for TDD