標籤:des style blog http color 使用
單例模式三種寫法:
第一種最簡單,但沒有考慮安全執行緒,在多線程時可能會出問題
public class Singleton{ private static Singleton _instance = null; private Singleton(){} public static Singleton CreateInstance() { if(_instance == null) { _instance = new Singleton(); } return _instance; }}
第二種考慮了安全執行緒,不過有點煩,但絕對是正規寫法,經典的一叉
public class Singleton{ private volatile static Singleton _instance = null; private static readonly object lockHelper = new object(); private Singleton(){} public static Singleton CreateInstance() { if(_instance == null) { lock(lockHelper) { if(_instance == null) _instance = new Singleton(); } } return _instance; }}
第三種可能是C#這樣的進階語言特有的,實在懶得出奇
public class Singleton{ private Singleton(){} public static readonly Singleton instance = new Singleton();}
一、 單例(Singleton)模式
單例模式的特點:
- 單例類只能有一個執行個體。
- 單例類必須自己建立自己的唯一執行個體。
- 單例類必須給所有其它對象提供這一執行個體。
單例模式應用:
- 每台電腦可以有若干個印表機,但只能有一個Printer Spooler,避免兩個列印工作同時輸出到印表機。
- 一個具有自動編號主鍵的表可以有多個使用者同時使用,但資料庫中只能有一個地方分配下一個主鍵編號。否則會出現主鍵重複。
二、 Singleton模式的結構:
Singleton模式包含的角色只有一個,就是Singleton。Singleton擁有一個私人建構函式,確保使用者無法通過new直接執行個體它。除此之外,該模式中包含一個靜態私人成員變數instance與靜態公有方法Instance()。Instance方法負責檢驗並執行個體化自己,然後儲存在靜態成員變數中,以確保只有一個執行個體被建立。(關於線程問題以及C#所特有的Singleton將在後面詳細論述)。
三、 程式舉例:
該程式示範了Singleton的結構,本身不具有任何實際價值。
// Singleton pattern -- Structural example using System;// "Singleton"class Singleton{ // Fields private static Singleton instance; // Constructor protected Singleton() {} // Methods public static Singleton Instance() { // Uses "Lazy initialization" if( instance == null ) instance = new Singleton(); return instance; }}/// <summary>/// Client test/// </summary>public class Client{ public static void Main() { // Constructor is protected -- cannot use new Singleton s1 = Singleton.Instance(); Singleton s2 = Singleton.Instance(); if( s1 == s2 ) Console.WriteLine( "The same instance" ); }}
四、 在什麼情形下使用單例模式:
使用Singleton模式有一個必要條件:在一個系統要求一個類只有一個執行個體時才應當使用單例模式。反過來,如果一個類可以有幾個執行個體共存,就不要使用單例模式。
注意:
不要使用單例模式存取全域變數。這違背了單例模式的用意,最好放到對應類的靜態成員中。
不要將資料庫連接做成單例,因為一個系統可能會與資料庫有多個串連,並且在有串連池的情況下,應當儘可能及時釋放串連。Singleton模式由於使用靜態成員儲存類執行個體,所以可能會造成資源無法及時釋放,帶來問題。
五、 Singleton模式在實際系統中的實現
下面這段Singleton代碼示範了負載平衡對象。在負載平衡模型中,有多台伺服器可提供服務,任務分配器隨機挑選一台伺服器提供服務,以確保任務均衡(實際情況比這個複雜的多)。這裡,任務分配執行個體只能有一個,負責挑選伺服器並分配任務。
// Singleton pattern -- Real World example using System;using System.Collections;using System.Threading;// "Singleton"class LoadBalancer{ // Fields private static LoadBalancer balancer; private ArrayList servers = new ArrayList(); private Random random = new Random(); // Constructors (protected) protected LoadBalancer() { // List of available servers servers.Add( "ServerI" ); servers.Add( "ServerII" ); servers.Add( "ServerIII" ); servers.Add( "ServerIV" ); servers.Add( "ServerV" ); } // Methods public static LoadBalancer GetLoadBalancer() { // Support multithreaded applications through // "Double checked locking" pattern which avoids // locking every time the method is invoked if( balancer == null ) { // Only one thread can obtain a mutex Mutex mutex = new Mutex(); mutex.WaitOne(); if( balancer == null ) balancer = new LoadBalancer(); mutex.Close(); } return balancer; } // Properties public string Server { get { // Simple, but effective random load balancer int r = random.Next( servers.Count ); return servers[ r ].ToString(); } }}/// <summary>/// SingletonApp test/// </summary>///public class SingletonApp{ public static void Main( string[] args ) { LoadBalancer b1 = LoadBalancer.GetLoadBalancer(); LoadBalancer b2 = LoadBalancer.GetLoadBalancer(); LoadBalancer b3 = LoadBalancer.GetLoadBalancer(); LoadBalancer b4 = LoadBalancer.GetLoadBalancer(); // Same instance? if( (b1 == b2) && (b2 == b3) && (b3 == b4) ) Console.WriteLine( "Same instance" ); // Do the load balancing Console.WriteLine( b1.Server ); Console.WriteLine( b2.Server ); Console.WriteLine( b3.Server ); Console.WriteLine( b4.Server ); }}
六、 C#中的Singleton模式
C#的獨特語言特性決定了C#擁有實現Singleton模式的獨特方法。這裡不再贅述原因,給出幾個結果:
方法一:
下面是利用.NET Framework平台優勢實現Singleton模式的代碼:
sealed class Singleton{ private Singleton(); public static readonly Singleton Instance=new Singleton();}
這使得代碼減少了許多,同時也解決了線程問題帶來的效能上損失。那麼它又是怎樣工作的呢?
注意到,Singleton類被聲明為sealed,以此保證它自己不會被繼承,其次沒有了Instance的方法,將原來_instance成員變數變成public readonly,並在聲明時被初始化。通過這些改變,我們確實得到了Singleton的模式,原因是在JIT的處理過程中,如果類中的static屬性被任何方法使用時,.NET Framework將對這個屬性進行初始化,於是在初始化Instance屬性的同時Singleton類執行個體得以建立和裝載。而私人的建構函式和readonly(唯讀)保證了Singleton不會被再次執行個體化,這正是Singleton設計模式的意圖。
(摘自:http://www.cnblogs.com/huqingyu/archive/2004/07/09/22721.aspx )
不過這也帶來了一些問題,比如無法繼承,執行個體在程式一運行就被初始化,無法實現延遲初始化等。
詳細情況可以參考微軟MSDN文章:《Exploring the Singleton Design Pattern》
方法二:
既然方法一存在問題,我們還有其它辦法。
public sealed class Singleton{ Singleton() { } public static Singleton GetInstance() { return Nested.instance; } class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); }}
這實現了延遲初始化,並具有很多優勢,當然也存在一些缺點。詳細內容請訪問:《Implementing the Singleton Pattern in C#》。文章包含五種Singleton實現,就模式、線程、效率、延遲初始化等很多方面進行了詳細論述。
參考連結:http://blog.csdn.net/zhuangzhineng/article/details/3927455