C#設計模式:單例模式

來源:互聯網
上載者:User

標籤:main   避免   led   c#   col   應該   on()   設計   pre   

在c#中的單例模式是指在一個AppDomain中只會存在一個經過執行個體化的對象。單例模式的作用的避免建立更多本來不用建立的對象,因為有一些對象在使用上沒有必要建立那麼多,一個就夠了。單例模式實現起來的話要遵循一下幾個特點:

. 單例類都只有一個private的無參建構函式. 類聲明為sealed(不是必須的). 類中有一個靜態變數儲存著所建立的執行個體的引用. 單例類會提供一個靜態方法或屬性來返回建立的執行個體的引用(eg.GetInstance)

根據這幾個特點,首先是方法1:

 public class Singleton    {        private static  Singleton _instance;        private Singleton()        {        }        public static Singleton Instance => _instance ?? (_instance = new Singleton());    }

這樣,調用Singleton的靜態屬性Instance可以擷取這個對象的唯一的執行個體,但是在多線程訪問中由於該操作不是原子的,還是會可能建立多個執行個體,所以應該在這個靜態屬性的邏輯中加入鎖(lock),這樣一來,問題解決了,但是鎖對效能的損耗不能忽視,於是,又出現了沒有鎖的並且效能較好的一種方法:

 public class AnotherSingleton    {        private static readonly AnotherSingleton _instance = new AnotherSingleton();               static AnotherSingleton()        {        }        private AnotherSingleton()        {                   }        public static AnotherSingleton Instance        {            get            {                return _instance;            }        }    }

具體方法是加入一個靜態建構函式,靜態函數的作用在於初始化類層級的靜態屬性或欄位,這種方法完美的解決了鎖帶來的效能損耗問題同時又實現了單例。

我的原則是有一個好用的就沒必要去展示其他不好用的例子了,用這個就夠了。

C#設計模式:單例模式

聯繫我們

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