Design Pattern-SingleTon === # 適配器模式(SingleTon) * 為一種創建模式 * 使用時機 : 程式中某一類別實體化唯一的時候使用 * 目的 : * 讓使用的實體化類別唯一 * 可是用在實體化資料庫或是開銷很大的類別 * 優點 : * 只有唯一一個實體化,減少了內存開銷及性能開銷 * 避免資源重複佔用 * 缺點 : * 一般沒有對外API導致擴展困難 * 只有一個實例所以測試困難 # Flow chart  # 舉例 ## 惡漢模式 * 通常在程式開始實做實體化 * 可以看到成是在global時已經做實體化,可以確保程式能第一時間使用, 但如果該實體化的類別在後續程式中沒有使用則會變成額化的性能開銷 ```cpp= #include <iostream> class EagerSingleton { public: // 刪除拷貝構造函數和賦值操作符,防止多個實例 EagerSingleton(const EagerSingleton&) = delete; EagerSingleton& operator=(const EagerSingleton&) = delete; // 提供全局訪問點 static EagerSingleton& getInstance() { return instance; } void showMessage() { std::cout << "Hello, I am an Eager Singleton!" << std::endl; } private: // 私有構造函數,防止外界實例化 EagerSingleton() { std::cout << "EagerSingleton instance created." << std::endl; } // 靜態成員變量,類加載時即創建 static EagerSingleton instance; }; // 初始化靜態成員變量 EagerSingleton EagerSingleton::instance; int main() { // 獲取唯一的 EagerSingleton 實例 EagerSingleton& singleton = EagerSingleton::getInstance(); EagerSingleton& singleton1 = EagerSingleton::getInstance(); singleton.showMessage(); return 0; } ``` ## 懶散模式 * 在有需要時才做實體化, 這樣可以叫隨意的調度什麼時候實體化該類別,但要注意線程的控制問題 * 如果多的線程在instance確認為null時會破壞Singleton的設計方式 ```cpp= #include <iostream> #include <mutex> class LazySingleton { public: // 刪除拷貝構造函數和賦值操作符,防止多個實例 LazySingleton(const LazySingleton&) = delete; LazySingleton& operator=(const LazySingleton&) = delete; // 提供全局訪問點 static LazySingleton& getInstance() { // 使用雙重檢查鎖定來確保線程安全 if (instance == nullptr) { std::lock_guard<std::mutex> lock(mutex); if (instance == nullptr) { instance = new LazySingleton(); } } return *instance; } void showMessage() { std::cout << "Hello, I am a Lazy Singleton!" << std::endl; } private: // 私有構造函數,防止外界實例化 LazySingleton() { std::cout << "LazySingleton instance created." << std::endl; } // 靜態成員變量和鎖 static LazySingleton* instance; static std::mutex mutex; }; // 初始化靜態成員變量 LazySingleton* LazySingleton::instance = nullptr; std::mutex LazySingleton::mutex; int main() { // 獲取唯一的 LazySingleton 實例 LazySingleton& singleton = LazySingleton::getInstance(); LazySingleton& singleton1 = LazySingleton::getInstance(); singleton.showMessage(); return 0; } ``` github : https://github.com/GU-Lin/Design_Pattern_Practice/tree/main/Creational/Singletone source : https://hypc-pub.github.io/design-patterns/patterns/singleton-pattern.html ###### tags : `Creational` `DesignPattern`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up