1. 程式人生 > >一個簡單的單例模式 類的編寫

一個簡單的單例模式 類的編寫

 單例模式(Singleton)是幾個建立模式中最對立的一個,它的主要特點不是根據使用者程式呼叫生成一個新的例項,而是控制某個型別的例項唯一性,通過上圖我們知道它包含的角色只有一個,就是Singleton,它擁有一個私有建構函式,這確保使用者無法通過new直接例項它。除此之外,該模式中包含一個靜態私有成員變數instance與靜態公有方法Instance()。Instance()方法負責檢驗並例項化自己,然後儲存在靜態成員變數中,以確保只有一個例項被建立。

class Singleton
    {
        private static Singleton instance;


        // Constructor
        protected Singleton() { }


        // Methods
        public static Singleton Instance()
        {
            /
            if (instance == null)
                instance = new Singleton();


            return instance;
        }

2)以上的方法比較簡單,但網上說執行緒不安全(偶不懂)下面貼一個執行緒安全的

/// <summary>
/// A thread-safe singleton class.
/// </summary>
public sealed class Singleton
{
    private static Singleton _instance = null;
    private static readonly object SynObject = new object();

    Singleton()
    {
    }

    /// <summary>
    /// Gets the instance.
    /// </summary>
    public static Singleton Instance
    {
        get
        {
            // Syn operation.
            lock (SynObject)
            {
                return _instance ?? (_instance = new Singleton());
            }
        }
    }
}

這樣是經典的Double-Checked Locking方法。

詳細參考:http://www.cnblogs.com/rush/archive/2011/10/30/2229565.html

講得非常的詳細,贊一個。