在C++中,可以通過以下幾種方式來實現單例模式:
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if(instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if(instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
class Singleton {
private:
static Singleton* instance;
static std::mutex mtx; // 互斥鎖
Singleton() {}
public:
static Singleton* getInstance() {
if(instance == nullptr) {
std::lock_guard<std::mutex> lock(mtx); // 上鎖
if(instance == nullptr) {
instance = new Singleton();
}
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
class Singleton {
private:
Singleton() {}
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};
這些是常見的幾種單例模式的實現方式,選擇哪種方式取決于具體的需求和場景。