Analytics

2012年11月13日 星期二

[Design Pattern]Creational Pattern-Singleton Design Pattern(唯一模式)

使用時機:
使用在必須確保物間的唯一性,例如:多個物件共用一個Connection物件以減少Server的負載,或確保Connection物件的唯一性
使用方式:
下方程式碼設計為當外部存取SingleTon Class的Instance屬性時,會傳回已存在的實體
  1. public sealed class SingleTon
  2.  
  3. {
  4.  
  5. private static SingleTon _instance = null;
  6.  
  7. // Made default constructor as private
  8.  
  9. private SingleTon()
  10.  
  11. {
  12.  
  13. }
  14.  
  15. /// <summary>
  16.  
  17. /// Single Instance
  18.  
  19. /// </summary>
  20.  
  21. public static SingleTon Instance
  22.  
  23. {
  24.  
  25. get
  26.  
  27. {
  28.  
  29. lock (_instance)
  30.  
  31. {
  32.  
  33. _instance = _instance ?? new SingleTon();
  34.  
  35. return _instance;
  36.  
  37. }
  38.  
  39. }
  40.  
  41. }
  42.  
  43. # region Rest of Implementation Logic
  44.  
  45. //Add As many method u want here as instance member.No need to make them static
  46.  
  47. # endregion
  48.  
  49. }
  50.  
c#程式碼參考來源:http://www.dotnetfunda.com/articles/article889-design-pattern-implementation-using-csharp.aspx

沒有留言:

熱門文章