學習設計模式,一直沒有機會寫一個單例模式。今天在控制台應用程式,寫個簡單的例子,Hi與Hello。 public sealed class At { private static At instance = null; public static At Instance { get { if (in ...
學習設計模式,一直沒有機會寫一個單例模式。
今天在控制台應用程式,寫個簡單的例子,Hi與Hello。
public sealed class At { private static At instance = null; public static At Instance { get { if (instance == null) { instance = new At(); } return instance; } } public void Hello() { Console.WriteLine("Hello"); } public void Hi() { Console.WriteLine("Hi"); } }Source Code
單例類,宣告為sealed,也就是說阻止其他類從該類繼承。對象只是本身。
public sealed class At { private static At instance = null; private static readonly object threadSafeLock = new object(); public static At Instance { get { lock (threadSafeLock) { if (instance == null) { instance = new At(); } return instance; } } } public void Hello() { Console.WriteLine("Hello"); } public void Hi() { Console.WriteLine("Hi"); } }Source Code
下麵內容於2017-12-12 08:10分添加:
補充,上面的寫法是每次加鎖,性能多少有些損失。 解決此問題可以加個判斷對象沒有實例化時加鎖。
public static At Instance { get { if (instance == null) { lock (threadSafeLock) { if (instance == null) { instance = new At(); } } } return instance; } }Source Code