相關代碼:
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<