懶惰執行緒安全單例(適用於 .NET 3.5 或更早版本的備用實現)
因為在 .NET 3.5 及更早版本中,你沒有 Lazy<T>
類,所以你使用以下模式:
public class Singleton
{
private Singleton() // prevents public instantiation
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
這是受 Jon Skeet 部落格文章的啟發。
因為 Nested
類是巢狀的並且是私有的,所以不會通過訪問 Sigleton
類的其他成員(例如,公共只讀屬性)來觸發單例例項的例項化。