首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 設計模式:單例模式泛型實作與執行驗證

     編輯:關於C語言

單例模式 (Singleton Pattern) 核心概念

定義:保證一個類別僅有一個實例,並提供一個訪問它的全域訪問點。

應用場景示例

保證一個類別僅有一個實例。透過泛型實現通用的單例基礎類別,任何類別只需繼承或配合使用即可獲得單例特性。

模式結構圖

單例模式類別圖

泛型單例實作:Singleton<T>

使用巢狀類別實現線程安全的延遲初始化:

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Singleton
{
    /// 
    /// 泛型實現單例模式
    /// 
    /// 需要實現單例的類別
    public class Singleton<T> where T : new()
    {
        /// 
        /// 返回類別的實例
        /// 
        public static T Instance
        {
            get { return SingletonCreator.instance; }
        }

        class SingletonCreator
        {
            internal static readonly T instance = new T();
        }
    }
}

設計亮點

  • 泛型通用性:where T : new() 約束確保 T 有無參數建構函式。
  • 線程安全:靜態唯讀欄位 instance 在 .NET 中保證線程安全初始化。
  • 延遲初始化:巢狀類別 SingletonCreator 只有在首次存取 Instance 時才會被載入並初始化。
  • 無鎖效能:避免了雙重檢查鎖定的複雜性與效能開銷。

測試程式碼與執行結果

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Pattern.Singleton;

public partial class Singleton : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 使用單例模式,保證一個類別僅有一個實例
        Response.Write(Singleton<Test>.Instance.Time);
        Response.Write("<br />");
        Response.Write(Singleton<Test>.Instance.Time);
        Response.Write("<br />");

        // 不用單例模式
        Test t = new Test();
        Response.Write(t.Time);
        Response.Write("<br />");
        Test t2 = new Test();
        Response.Write(t2.Time);
        Response.Write("<br />");
    }
}

public class Test
{
    private DateTime _time;

    public Test()
    {
        System.Threading.Thread.Sleep(3000);
        _time = DateTime.Now; 
    }

    public string Time
    {
        get { return _time.ToString(); }
    }
}

執行結果

2007-2-10 22:35:11
2007-2-10 22:35:11
2007-2-10 22:35:14
2007-2-10 22:35:17

結果分析

  • 前兩行時間相同:Singleton<Test>.Instance 返回同一實例,建構函式只執行一次(含 3 秒 Sleep)。
  • 後兩行時間相差 3 秒:每次 new Test() 都建立新實例,建構函式各執行一次。

參考資源

DoFactory 單例模式

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved