單例模式確保某類全局僅有一實例,並提供全局訪問點。是面試高頻考點,也是最基礎的創建型模式。
new 實例化。static Singleton* _instance 唯一實例緩存。Instance() 惰性初始化並返回實例。class Singleton {
public:
static Singleton* Instance() {
if (_instance == 0) _instance = new Singleton();
return _instance;
}
protected:
Singleton() { cout << "Singleton..." << endl; }
private:
static Singleton* _instance;
};
Singleton* Singleton::_instance = 0;
protected 構造函數允許繼承,若不需繼承可用 private。this 指針,可直接類名調用。Instance() 才創建實例(惰性單例)。std::call_once、C++11 局部靜態變量。atexit 註冊銷毀。理解單例本質是「控制實例化過程」,面試時能手寫基礎版並討論線程安全優化即可過關。