單例模式c++實現

东岸發表於2024-05-23

單例模式是一種建立型設計模式,它保證一個類僅有一個例項,並提供一個全域性訪問點來訪問這個唯一例項。下面是一個簡單的C++實現單例模式的例子:

cpp

include

include

class Singleton {
private:
static Singleton* instance;
static std::mutex mtx;

Singleton() {} // 私有建構函式,防止外部建立例項
Singleton(const Singleton&) = delete; // 刪除複製建構函式
Singleton& operator=(const Singleton&) = delete; // 刪除賦值運算子

public:
static Singleton* getInstance() {
std::lock_guardstd::mutex lock(mtx); // 使用互斥鎖保證執行緒安全
if (!instance) {
instance = new Singleton();
}
return instance;
}

void doSomething() {
    std::cout << "Singleton instance is doing something." << std::endl;
}

};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;

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 not the same instance." << std::endl;
}

s1->doSomething();
s2->doSomething();

delete s1; // 注意:通常我們不會顯式刪除單例物件,除非你確定應用程式即將結束
return 0;

}
在這個例子中,我們使用了互斥鎖(std::mutex)來保證在多執行緒環境下getInstance方法的執行緒安全性。當getInstance方法被首次呼叫時,它會建立一個新的Singleton例項並將其賦值給靜態成員變數instance。在後續的呼叫中,getInstance方法會返回已經存在的例項。

注意,單例模式通常用於那些只需要一個例項的類,例如配置管理類、日誌記錄類等。然而,過度使用單例模式可能會導致程式碼難以理解和維護,因此在使用時應謹慎考慮。

相關文章