分享一个单例模型类 Singleton

本文介绍了一种在 C# 中实现多实例单例模式的方法,通过创建泛型基类 `Singleton<T>` 来简化单例模式的实现过程,并支持通过 ID 创建多个不同的单例对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每个对象都写单例,单调又无聊。因此我写了个基类,只要集成,就实现了单例。

而且支持多单例(不同id对应不同的单例)

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(T));

                    ((Singleton
<T>)i)._id = id;

                    T it 
= (T)i;

                    dict.Add(id, it);

                    
return it;
                }
            }
        }

        
public T this[int index]
        {
            
get
            {
                
if (index < 0 || index > dict.Keys.Count - 1)
                    
return Instance;

                
int coutner = 0;

                
foreach (string key in dict.Keys)
                {
                    
if (coutner >= index)
                        
return dict[key];

                    coutner
++;
                }

                
return Instance;

            }
        }

        
public string SingletonId
        {
            
get { return _id; }
        }
    }
}


使用方法:

    class testclass
    {
        
private void test()
        {
            Hello.Instance.Test();

            Hello.Instance[
"id"].Test();
        }
    }

    
public class Hello : Singleton<Hello>
    {

        
public void Test()
        {
            Console.Write(
"hello");
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值