单例模式(Singleton Pattern)是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点来访问该实例。
使用静态局部变量来确保线程安全。这是 C++ 中最常用的单例模式实现方法。
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
private:
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
使用双重检查锁机制来减少获取锁的开销。这是一种高效的单例模式实现方法,但需要注意锁的粒度和性能。
class Singleton {
public:
static Singleton& getInstance() {
if (!instance) {
std::lock_guard<std::mutex> lock(mutex);
if (!instance) {
instance = new Singleton();
}
}
return *instance;
}
private:
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* instance;
static std::mutex mutex;
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex;
不使用任何同步机制,直接返回实例。这是一种简单的单例模式实现方法,但不安全,可能会导致多个实例创建。
class Singleton {
public:
static Singleton& getInstance() {
if (!instance) {
instance = new Singleton();
}
return *instance;
}
private:
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* instance;
};
Singleton* Singleton::instance = nullptr;
使用枚举来确保单例实例只创建一次。这是一种巧妙的单例模式实现方法,但需要注意枚举的使用场景。
class Singleton {
public:
static Singleton& getInstance() {
return instance;
}
private:
enum class SingletonEnum { INSTANCE };
static Singleton instance;
};
Singleton Singleton::instance;
使用嵌套类来确保单例实例只创建一次。这是一种高效的单例模式实现方法,但需要注意嵌套类的使用场景。
class Singleton {
public:
static Singleton& getInstance() {
return SingletonHelper::instance;
}
private:
class SingletonHelper {
public:
static Singleton instance;
};
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
Singleton Singleton::SingletonHelper::instance;
使用 std::call_once 来确保单例实例只创建一次。这是一种高效的单例模式实现方法,但需要注意 std::call_once 的使用场景。
class Singleton {
public:
static Singleton& getInstance() {
std::call_once(flag, []() {
instance = new Singleton();
});
return *instance;
}
private:
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* instance;
static std::once_flag flag;
};
Singleton* Singleton::instance = nullptr;
std::once_flag Singleton::flag;