確保類別在整個系統中僅存在一個實例,並提供全域存取點。適用場景:滑鼠、調製解調器連線、視窗管理器、鍵盤裝置等系統級唯一資源。
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton(); // 防止外部建構
Singleton(const Singleton&); // 防止複製
Singleton& operator=(const Singleton&); // 防止賦值
private:
static Singleton* pinstance;
};
Singleton* Singleton::pinstance = nullptr;
Singleton* Singleton::Instance() {
if (pinstance == nullptr) {
pinstance = new Singleton; // 延遲初始化
}
return pinstance;
}
特點: 延遲初始化、執行緒不安全(多執行緒需加鎖)、需手動 delete 否則記憶體洩漏且析構函數不會被呼叫。
Singleton* Singleton::Instance() {
static Singleton inst; // C++ 標準保證第一次呼叫時建構,程式結束時自動解構
return &inst;
}
優勢:
pinstance 靜態成員。修改 Instance() 邏輯即可支援固定數量實例(如連線池最多 5 個):
Singleton* Singleton::Instance() {
static std::vector<Singleton*> instances;
if (instances.size() < MAX_INSTANCES) {
instances.push_back(new Singleton);
}
return instances[current_index++ % MAX_INSTANCES];
}
std::call_once 或雙重檢查鎖定模式。