靜態Singleton模式

來源:互聯網
上載者:User
什麼是靜態單例模式?

靜態單例模式(Static Singleton Pattern)是我在實踐中總結的模式,主要解決的問題是在預Crowdsourced Security Testing道某依賴項為單例應用時,通過靜態緩衝該依賴項來提供訪問。當然,解決該問題的辦法有很多,這隻是其中一個。

實現細節
  /// <summary>  /// 靜態單例  /// </summary>  /// <typeparam name="TClass">單例類型</typeparam>  public static class Singleton<TClass> where TClass : class, new()  {    private static readonly object _lock = new object();    private static TClass _instance = default(TClass);    /// <summary>    /// 擷取單例執行個體    /// </summary>    public static TClass GetInstance()    {      return Instance;    }    /// <summary>    /// 單例執行個體    /// </summary>    public static TClass Instance    {      get      {        if (_instance == null)        {          lock (_lock)          {            if (_instance == null)            {              _instance = new TClass(); // must be public constructor            }          }        }        return _instance;      }    }    /// <summary>    /// 設定單例執行個體    /// </summary>    /// <param name="instance">單例執行個體</param>    public static void Set(TClass instance)    {      lock (_lock)      {        _instance = instance;      }    }    /// <summary>    /// 重設單例執行個體    /// </summary>    public static void Reset()    {      lock (_lock)      {        _instance = default(TClass);      }    }  }
應用測試
  class Program  {    interface IInterfaceA    {      string GetData();    }    class ClassA : IInterfaceA    {      public string GetData()      {        return string.Format("This is from ClassA with hash [{0}].", this.GetHashCode());      }    }    static void Main(string[] args)    {      string data1 = Singleton<ClassA>.GetInstance().GetData();      Console.WriteLine(data1);      string data2 = Singleton<ClassA>.GetInstance().GetData();      Console.WriteLine(data2);      Console.ReadKey();    }  }
測試結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.