首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 通用單例模式實作:Singleton<T> 完整程式碼

     編輯:C# 入門

設計特點

  • 泛型實作,適用於任意參考型別。
  • 雙重檢查鎖定確保執行緒安全。
  • 內建字典支援多鍵值單例管理。
  • 索引器提供直觀存取介面。

完整程式碼

using System;
using System.Collections.Generic;

namespace Pixysoft.DesignPattern
{
    public class Singleton<T> where T : class, new()
    {
        private readonly Dictionary<string, T> _dict = new Dictionary<string, T>();
        private string _id = null;
        private static volatile object _instance;
        private static readonly object _syncRoot = new Object();

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                            _instance = Activator.CreateInstance<T>();
                    }
                }
                return (T)_instance;
            }
        }

        public T this[string id]
        {
            get
            {
                if (string.IsNullOrEmpty(id))
                    return Instance;

                id = id.Trim().ToUpper();
                lock (_syncRoot)
                {
                    if (_dict.ContainsKey(id))
                        return _dict[id];

                    T newInstance = Activator.CreateInstance<T>();
                    _dict.Add(id, newInstance);
                    return newInstance;
                }
            }
        }
    }
}

使用範例

// 取得預設單例
var service = Singleton<MyService>.Instance;

// 依鍵值取得/建立具名單例
var configA = Singleton<Config>["A"];
var configB = Singleton<Config>["B"];

關鍵技術點解析

  1. volatile + 雙重檢查鎖定:防止指令重排序導致的執行緒安全問題。
  2. Activator.CreateInstance<T>():動態建立泛型型別實例,需型別有無參數建構函式。
  3. 字典快取:以不區分大小寫的鍵值管理多個具名實例。

此實作兼具效能與彈性,是專案中管理服務、配置等單一實例的理想基礎類別。

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