類別將建構函式標記為 private,外部無法直接 new 實例,這有什麼特別用途?
私有建構函式配合靜態工廠方法,確保整個應用程式域中僅存在一個實例:
public sealed class Singleton {
private static readonly Singleton _instance = new Singleton();
private Singleton() { } // 私有建構函式
public static Singleton Instance => _instance;
public void DoSomething() { /* ... */ }
}
// 使用方式
Singleton.Instance.DoSomething();
Math、File)。Builder 類別逐步建構複雜物件。sealed 徹底封鎖繼承與實例化。私有建構函式最經典用途是單例模式,確保全域唯一實例;亦用於工廠、建造者等創建型模式,集中控制物件建構邏輯。