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"];
此實作兼具效能與彈性,是專案中管理服務、配置等單一實例的理想基礎類別。