SingletonCollection.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. namespace IFramework.Singleton
  4. {
  5. /// <summary>
  6. /// 单例合集
  7. /// </summary>
  8. public static class SingletonCollection
  9. {
  10. static Dictionary<Type, ISingleton> pairs;
  11. static SingletonCollection()
  12. {
  13. pairs = new Dictionary<Type, ISingleton>();
  14. // Framework.onDispose += Dispose;
  15. }
  16. /// <summary>
  17. /// 注入单例
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. /// <param name="singleton"></param>
  21. public static void Set<T>(T singleton) where T : ISingleton
  22. {
  23. Type type = typeof(T);
  24. if (!pairs.ContainsKey(type))
  25. pairs.Add(type, singleton);
  26. else
  27. throw new Exception("Singleton Err");
  28. }
  29. /// <summary>
  30. /// 注销一个单例
  31. /// </summary>
  32. /// <typeparam name="T"></typeparam>
  33. public static void Dispose<T>() where T : ISingleton
  34. {
  35. Type type = typeof(T);
  36. if (pairs.ContainsKey(type))
  37. {
  38. pairs[type].Dispose();
  39. pairs.Remove(type);
  40. }
  41. else
  42. throw new Exception("SingletonPool dispose Err "+typeof(T));
  43. }
  44. /// <summary>
  45. /// 注销所有单例
  46. /// </summary>
  47. public static void Dispose()
  48. {
  49. foreach (var item in pairs.Values)
  50. {
  51. item.Dispose();
  52. }
  53. pairs.Clear();
  54. }
  55. }
  56. }