設計模式(5)單例模式
阿新 • • 發佈:2018-11-09
模式介紹
單例模式是一種建立型設計模式,其中一個類只保證只有一個例項,該例項可以全域性訪問。
這意味著該模式強制特定物件不具有可訪問的建構函式,並且對該物件執行的任何訪問都是在該物件的同一例項上執行的。
示例
我們模擬一下餐館裡用於通知上菜鈴鐺,它在櫃檯上只有一個。
下面程式碼中syncRoot是為了執行緒安全。
/// <summary> /// Singleton /// </summary> public sealed class TheBell { private static TheBell bellConnection; private static object syncRoot = new Object(); private TheBell() { } /// <summary> /// We implement this method to ensure thread safety for our singleton. /// </summary> public static TheBell Instance { get { lock(syncRoot) { if(bellConnection == null) { bellConnection = new TheBell(); } } return bellConnection; } } public void Ring() { Console.WriteLine("Ding! Order up!"); } }
總結
單例模式的物件只能是一個例項。它不是全域性變數,許多人認為它們違反了軟體設計的原則,但它確實有其用途,因此應謹慎使用。
原始碼
https://github.com/exceptionnotfound/DesignPatterns/tree/master/Singleton
原文
https://www.exceptionnotfound.net/singleton-the-daily-design-pattern/