2011-02-18 31 views
1

我想收集更多的變體來創建單例類。 您能否以您的意見在C#中提供給我最好的創作方式?C中的單例#

謝謝。

public sealed class Singleton 
{ 
    Singleton _instance = null; 

    public Singleton Instance 
    { 
     get 
     { 
      if(_instance == null) 
       _instance = new Singleton(); 

      return _instance; 
     } 
    } 

    // Default private constructor so only we can instanctiate 
    private Singleton() { } 

    // Default private static constructor 
    private static Singleton() { } 
} 
+0

Mmh的......聽起來像是已經要求.. – digEmAll 2011-02-18 12:01:02

+0

@Klaus:這個實現是* not *罰款......屬性和字段是非靜態的......你怎麼能創建一個實例? – 2011-02-18 12:03:21

+0

@Jon,對,「實例」應該是靜態的。沒有注意到。將編輯我的帖子。 – 2011-02-18 12:07:12

回答

12

我對此有一個entire article,您可能會覺得這很有用。

哦,並儘量避免使用Singleton模式一般,由於其疼痛可測性等:)

0

這裏看看:http://www.yoda.arachsys.com/csharp/singleton.html

public sealed class Singleton 
{ 
    static readonly Singleton instance=new Singleton(); 

    // Explicit static constructor to tell C# compiler 
    // not to mark type as beforefieldinit 
    static Singleton() 
    { 
    } 

    Singleton() 
    { 
    } 

    public static Singleton Instance 
    { 
     get 
     { 
      return instance; 
     } 
    } 
}