2010-05-25 36 views

回答

2
public class Singleton 
{ 
    static readonly Singleton _instance = new Singleton(); 

    static Singleton() { } 

    private Singleton() { } 

    static public Singleton Instance 
    { 
     get { return _instance; } 
    } 
} 
1

直到最近,我才知道,辛格爾頓被許多人認爲是一個反模式,應該避免。更清潔的解決方案可能是使用DI或其他功能。即使你單身去剛讀了這個有趣的討論,從C# in Depth轉述 What is so bad about singletons?

2

: 有各種不同的方式實現在C#Singleton模式,從 不是線程安全的,完全懶洋洋地加載,thread-安全,簡單和高性能的版本。

最好的版本 - 使用.NET 4的懶惰類型:

public sealed class Singleton 
{ 
    private static readonly Lazy<Singleton> lazy = 
     new Lazy<Singleton>(() => new Singleton()); 

    public static Singleton Instance { get { return lazy.Value; } } 

    private Singleton() 
    { 
    } 
} 

它的簡單和表現良好。它還允許您檢查實例是否已使用IsValueCreated屬性創建,如果需要的話。

相關問題