.Net 單例模式(Singleton)

來源:互聯網
上載者:User

 

目錄
  1. 定義
  2. UML
  3. 參與者
  4. 樣本
定義:

單例模式的意思就是只有一個執行個體。單例模式確保某一個類只有一個執行個體,而且自行執行個體化並向整個系統提供這個執行個體。這個類稱為單例類。

 

應用:

每台電腦可以有若干個印表機,但只能有一個Printer Spooler, 以避免兩個列印工作同時輸出到印表機中。每台電腦可以有若干傳真卡,但是只應該有一個軟體負責管理傳真卡,以避免出現兩份傳真作業同時傳到傳真卡中的情況。每台電腦可以有若干通訊連接埠,系統應當集中管理這些通訊連接埠,以避免一個通訊連接埠同時被兩個請求同時調用。

 

UML:

 

參與者:

Singleton 角色:定義一個執行個體操作,同一段時間只能被一個客戶訪問。

 

樣本:
代碼using System; namespace SingletonPattern{  /// <summary>  /// Singleton Design Pattern.  /// </summary>  class MainApp  {    static void Main()    {      // Constructor is protected -- cannot use new      Singleton s1 = Singleton.Instance();      Singleton s2 = Singleton.Instance();       // Test for same instance      if (s1 == s2)      {        Console.WriteLine("同一個執行個體");      }       Console.ReadKey();    }  }   class Singleton  {    private static Singleton _instance;     // Constructor is 'protected'    protected Singleton()    {    }     public static Singleton Instance()    {      // Uses lazy initialization.      // Note: this is not thread safe.      if (_instance == null)      {        _instance = new Singleton();      }       return _instance;    }  }}

實際運用:

代碼// Singleton pattern -- Real World exampleusing System;using System.Collections.Generic;using System.Threading; namespace DoFactory.GangOfFour.Singleton.RealWorld{  /// <summary>  /// MainApp startup class for Real-World  /// Singleton Design Pattern.  /// </summary>  class MainApp  {    /// <summary>    /// Entry point into console application.    /// </summary>    static void Main()    {      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\n");      }       // Load balance 15 server requests      LoadBalancer balancer = LoadBalancer.GetLoadBalancer();      for (int i = 0; i < 15; i++)      {        string server = balancer.Server;        Console.WriteLine("Dispatch Request to: " + server);      }       // Wait for user      Console.ReadKey();    }  }   /// <summary>  /// The 'Singleton' class  /// </summary>  class LoadBalancer  {    private static LoadBalancer _instance;    private List<string> _servers = new List<string>();    private Random _random = new Random();     // Lock synchronization object    private static object syncLock = new object();     // Constructor (protected)    protected LoadBalancer()    {      // List of available servers      _servers.Add("ServerI");      _servers.Add("ServerII");      _servers.Add("ServerIII");      _servers.Add("ServerIV");      _servers.Add("ServerV");    }     public static LoadBalancer GetLoadBalancer()    {      // Support multithreaded applications through      // 'Double checked locking' pattern which (once      // the instance exists) avoids locking each      // time the method is invoked      if (_instance == null)      {        lock (syncLock)        {          if (_instance == null)          {            _instance = new LoadBalancer();          }        }      }       return _instance;    }     // Simple, but effective random load balancer    public string Server    {      get      {        int r = _random.Next(_servers.Count);        return _servers[r].ToString();      }    }  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.