Singleton 模式在多執行緒環境中具高價值。ACE 框架大量使用 ACE_Singleton 模板將一般類別轉為 Singleton 行為,優化後效能較標準互斥版本提升 15 倍。C++/CLI 實作同樣不可或缺。
#pragma once
/** \class sidle::Singleton
\brief Singleton (Double-Checked Locking)
\author 吳爾平
\version 1.0
\date 2005.02.08
*/
namespace sidle {
using namespace System;
using namespace System::Threading;
template<typename _T>
ref class Singleton {
public:
static _T^ Instance() {
if (_instance == nullptr) {
_mut->WaitOne();
try {
if (_instance == nullptr) {
_instance = gcnew _T();
}
}
finally {
_mut->ReleaseMutex();
}
}
return _instance;
}
protected:
Singleton() {}
static _T^ _instance;
static Mutex^ _mut = gcnew Mutex();
}; // ref class Singleton
}; // namespace sidle
template<typename _T> ref class Singleton 可套用至任意參考型別。nullptr 檢查避免不必要鎖定開銷;進入鎖定後第二次檢查確保單一實例化。WaitOne()/ReleaseMutex() 確保執行緒安全,finally 區塊保證釋放。Singleton() {} 防止外部直接實例化。_mut = gcnew Mutex() 於類別載入時建立,執行緒安全。ref class MyService { /* ... */ };
MyService^ svc = sidle::Singleton<MyService>::Instance();