单例模式
懒汉式单例模式的特点是在第一次使用时才创建实例,而饿汉式单例模式在类加载的时候就创建实例。
懒汉式
使用场景:
1、当单例对象的创建和初始化过程比较耗时时,可以使用懒汉式单例模式。因为它可以延迟对象的创建,避免不必要的开销。
2、当单例对象的创建依赖于外部条件,需要在第一次使用时才能确定时,可以使用懒汉式单例模式。
优势:
1、在第一次使用时才创建实例,避免了不必要的内存开销。
2、只有在需要时才创建实例,避免了不必要的初始化和耗时操作。
劣势:
1、在多线程环境下,需要考虑线程安全性,需要使用同步机制来保证只有一个实例被创建。
2、使用同步机制可能会影响性能。
Code
#include <iostream>
class Singleton {
private:
static Singleton* instance;
Singleton() {} // private constructor to prevent instantiation
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
int main() {
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();
if (s1 == s2) {
std::cout << "s1 and s2 are the same instance" << std::endl;
} else {
std::cout << "s1 and s2 are different instances" << std::endl;
}
return 0;
}
饿汉式
使用场景:
1、当单例对象的创建和初始化过程比较简单,且在整个程序的生命周期内都会被使用时,可以使用饿汉式单例模式。
2、当单例对象的创建不依赖于外部条件,可以在类加载的时候就确定时,可以使用饿汉式单例模式。
优势:
1、在类加载的时候就创建实例,避免了多线程环境下的同步问题。
2、由于在类加载的时候就创建实例,因此可以保证实例的唯一性。
劣势:
1、在程序启动时就创建实例,可能会造成不必要的内存开销。
2、如果单例对象的创建和初始化过程比较耗时,可能会影响程序启动的性能。
Code
#include <iostream>
class Singleton {
private:
static Singleton* instance;
Singleton() {} // private constructor to prevent instantiation
public:
static Singleton* getInstance() {
return instance;
}
};
Singleton* Singleton::instance = new Singleton();
int main() {
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();
if (s1 == s2) {
std::cout << "s1 and s2 are the same instance" << std::endl;
} else {
std::cout << "s1 and s2 are different instances" << std::endl;
}
return 0;
}