Singleton.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. namespace IFramework.Singleton
  3. {
  4. /// <summary>
  5. /// 单例基类
  6. /// </summary>
  7. /// <typeparam name="T"></typeparam>
  8. public abstract class Singleton<T> : Unit, ISingleton where T : Singleton<T>
  9. {
  10. private static T _instance;
  11. static object lockObj = new object();
  12. /// <summary>
  13. /// 实例
  14. /// </summary>
  15. public static T instance
  16. {
  17. get
  18. {
  19. lock (lockObj)
  20. if (_instance == null)
  21. {
  22. _instance = SingletonCreator.CreateSingleton<T>();
  23. SingletonCollection.Set(_instance);
  24. }
  25. return _instance;
  26. }
  27. }
  28. /// <summary>
  29. /// ctror
  30. /// </summary>
  31. protected Singleton() { }
  32. /// <summary>
  33. /// 初始化
  34. /// </summary>
  35. protected virtual void OnSingletonInit() { }
  36. /// <summary>
  37. /// 注销
  38. /// </summary>
  39. public override void Dispose()
  40. {
  41. base.Dispose();
  42. if (!disposed)
  43. {
  44. _instance = null;
  45. }
  46. }
  47. void ISingleton.OnSingletonInit()
  48. {
  49. OnSingletonInit();
  50. }
  51. }
  52. }