public sealed class Singleton
{
Singleton() { }
public static Singleton Instance => SingletonCreator.instance;
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly Singleton instance = new Singleton();
}
}
將具體型別 Singleton 替換為型別參數 T,並加上 where T : new() 約束:
public class SingletonProvider where T : new()
{
SingletonProvider() { }
public static T Instance => SingletonCreator.instance;
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}
new() 約束的類別皆可透過 SingletonProvider<T>.Instance 取得單例。SingletonCreator 靜態建構子由 CLR 保證執行緒安全、延遲初始化。此模式展示泛型如何消除樣板程式碼,提升可維護性。