public sealed class Singleton1
{
private static Singleton1 _instance;
private Singleton1() { }
public static Singleton1 Instance
{
get
{
if (_instance == null) _instance = new Singleton1(); // Race condition!
return _instance;
}
}
}
public sealed class Singleton2
{
private static volatile Singleton2 _instance; // volatile 防止指令重排
private static readonly object _lock = new object();
private Singleton2() { }
public static Singleton2 Instance
{
get
{
if (_instance == null) // 第一次檢查 (無鎖,快)
{
lock (_lock)
{
if (_instance == null) // 第二次檢查 (鎖內)
_instance = new Singleton2();
}
}
return _instance;
}
}
}
關鍵:`volatile` 確保寫入 `_instance` 完成前,其他執行緒不可見到非 null 參考 (防止指令重排最佳化)。.NET 2.0+ 記憶體模型保證 DCL 正確。
public sealed class Singleton3
{
private static readonly Singleton3 _instance = new Singleton3();
static Singleton3() { } // 明確靜態建構子 → beforefieldinit 控制時機
private Singleton3() { }
public static Singleton3 Instance => _instance;
}
public sealed class Singleton4
{
private Singleton4() { }
public static Singleton4 Instance => Nested.Instance;
private class Nested
{
static Nested() { }
internal static readonly Singleton4 Instance = new Singleton4();
}
}
利用巢狀類別載入時機:外部類別首次存取 `Nested.Instance` 時才載入 `Nested`,觸發靜態建構子。零鎖、零 `volatile`、語意清晰。
public sealed class Singleton5
{
private Singleton5() { }
private static readonly Lazy _lazy = new Lazy(() => new Singleton5(), LazyThreadSafetyMode.ExecutionAndPublication);
public static Singleton5 Instance => _lazy.Value;
}
// 適用於初始化涉及 I/O (資料庫連線、HTTP 呼叫、讀取設定檔)
public sealed class AsyncSingleton
{
private AsyncSingleton() { }
private static readonly AsyncLazy _lazy = new AsyncLazy(async () =>
{
var instance = new AsyncSingleton();
await instance.InitializeAsync(); // 非同步初始化
return instance;
});
public static Task GetInstanceAsync() => _lazy.Value;
private Task InitializeAsync() { /* ... */ return Task.CompletedTask; }
}
// 簡易 AsyncLazy 實作 (或引用 Nito.AsyncEx)
public class AsyncLazy : Lazy>
{
public AsyncLazy(Func> factory) : base(() => Task.Run(factory)) { }
public TaskAwaiter GetAwaiter() => Value.GetAwaiter();
}
// ASP.NET Core / Modern DI
services.AddSingleton(); // 容器管理生命週期,單一實例
// 控制器/服務建構子注入
public class MyController : ControllerBase
{
private readonly IMyService _svc;
public MyController(IMyService svc) => _svc = svc;
}
**現代架構首選 DI 容器管理單例**,避免靜態 `Instance` 造成強耦合、難以測試、替換實作。
| ✅ 適合 | ❌ 反模式 |
|---|---|
| 日誌記錄器、設定管理、快取、連線池、硬體存取包裝 | 業務邏輯服務 (應用 DI)、資料庫 Context (應為 Scoped)、大型狀態物件 |
| 無狀態工具類、統計計數器 | 為了「方便全域存取」濫用單例 (全域變數偽裝) |
單例模式看似簡單,執行緒安全、延遲初始化、例外處理、非同步支援、DI 整合等細節決定生產級品質。選對工具,專注業務邏輯。