public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null) instance = new Singleton();
return instance;
}
}
}
優點:延遲實例化、可在屬性中加入邏輯(如子類實例化)。
缺點:多線程下 if (instance == null) 可能同時通過,產生多個實例。
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance => instance;
}
特點:
readonly 確保僅在靜態建構函式或宣告時賦值一次。sealed 禁止繼承,避免破壞單例語意。這是 .NET 中最推薦的寫法,簡潔高效。
public sealed class Singleton
{
private static volatile Singleton instance;
private static readonly object syncRoot = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
關鍵細節:
volatile 防止指令重排序,確保其他執行緒看到完全初始化後的物件。syncRoot 而非 typeof(Singleton),避免跨 AppDomain 死鎖風險。if 減少鎖定開銷,僅首次建立時進入關鍵區。| 寫法 | 線程安全 | 延遲載入 | 建構彈性 | 推薦指數 |
|---|---|---|---|---|
| 懶漢式 | ❌ | ✅ | ✅ | ⭐ |
| 靜態初始化 | ✅ (CLR) | ✅ (首次靜態存取) | ❌ (無法自訂建構邏輯) | ⭐⭐⭐⭐⭐ |
| Double-Check Locking | ✅ | ✅ | ✅ | ⭐⭐⭐⭐ |
Lazy<T>(.NET 4.0+ 內建支援)。