使用在必須確保物間的唯一性,例如:多個物件共用一個Connection物件以減少Server的負載,或確保Connection物件的唯一性
使用方式:
下方程式碼設計為當外部存取SingleTon Class的Instance屬性時,會傳回已存在的實體
c#程式碼參考來源:http://www.dotnetfunda.com/articles/article889-design-pattern-implementation-using-csharp.aspx
- public sealed class SingleTon
- {
- private static SingleTon _instance = null;
- // Made default constructor as private
- private SingleTon()
- {
- }
- /// <summary>
- /// Single Instance
- /// </summary>
- public static SingleTon Instance
- {
- get
- {
- lock (_instance)
- {
- _instance = _instance ?? new SingleTon();
- return _instance;
- }
- }
- }
- # region Rest of Implementation Logic
- //Add As many method u want here as instance member.No need to make them static
- # endregion
- }
沒有留言:
張貼留言