public class Singleton {
private Singleton() {}
public static readonly Singleton instance = new Singleton(); // 靜態初始化器
}
| 模式 | 代碼要點 | 線程安全 | 延遲初始化 | 性能 |
|---|---|---|---|---|
| 靜態 readonly (題主) | `static readonly Instance = new T();` | ✅ CLR 保證 | ❌ 類加載即初始化 | 極高 (無鎖、無判斷) |
| 雙重檢查鎖 (DCL) | `if (instance==null) lock { if(instance==null) instance=new T(); }` | ✅ `volatile` + 鎖 | ✅ 首次調用 | 高 (首次鎖,後續無鎖) |
| 嵌套類 (推薦) | `class Holder { static readonly Instance = new T(); }` | ✅ CLR 保證 | ✅ 訪問 Holder 時初始化 | 極高 (無鎖、真正延遲) |
| Lazy<T> (現代首選) | `static readonly Lazy | ✅ 內部實現 | ✅ `lazy.Value` 時 | 高、語義清晰 |
public sealed class Singleton {
private Singleton() {}
public static Singleton Instance => Nested.instance;
private class Nested {
static Nested() {} // 顯式靜態構造函數觸發延遲
internal static readonly Singleton instance = new Singleton();
}
}
public sealed class Singleton {
private Singleton() {}
private static readonly Lazy _lazy =
new Lazy(() => new Singleton(), LazyThreadSafetyMode.ExecutionAndPublication);
public static Singleton Instance => _lazy.Value;
}
題主代碼是**飽漢模式**變體 (靜態初始化),線程安全但非延遲。面試中若要求「多線程並發下的懶漢單例」,正確答案是 **嵌套類** 或 **Lazy<T>**,雙重檢查鎖次之 (需 `volatile`),單純 `static readonly` 不符合「懶漢」定義。