当前位置:编程学习 > C#/ASP.NET >>

分享一个单例模型类Singleton代码

相关代码:

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

namespace Pixysoft.DesignPattern
{
    public class Singleton<T>
    {
        private Dictionary<string, T> dict = new Dictionary<string, T>();

        private string _id = null;

        private static volatile object instance;

        private static object syncRoot = new Object();

        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        instance = Activator.CreateInstance(typeof(T));
                    }
                }

                return (T)instance;

            }
        }

        public T this[string id]
        {
            get
            {
                //如果是null,表示自己,则直接返回Instance

                if (string.IsNullOrEmpty(id))
                    return Instance;

                id = id.Trim().ToUpper();

                lock (syncRoot)
                {
                    if (dict.ContainsKey(id))
                        return dict[id];

                    object i = Activator.CreateInstance(typeof<

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,