Singleton.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. namespace ET
  3. {
  4. // 定义一个接口 ISingleton,用于实现单例模式
  5. public interface ISingleton: IDisposable
  6. {
  7. // 注册单例对象
  8. void Register();
  9. // 销毁单例对象
  10. void Destroy();
  11. // 判断单例对象是否已经被销毁
  12. bool IsDisposed();
  13. }
  14. // 定义一个抽象类 Singleton<T>,继承自 ISingleton 接口,用于创建泛型的单例对象
  15. public abstract class Singleton<T>: ISingleton where T: Singleton<T>, new()
  16. {
  17. private bool isDisposed;
  18. [StaticField]
  19. private static T instance;
  20. public static T Instance
  21. {
  22. get
  23. {
  24. return instance;
  25. }
  26. }
  27. void ISingleton.Register()
  28. {
  29. if (instance != null)
  30. {
  31. throw new Exception($"singleton register twice! {typeof (T).Name}");
  32. }
  33. instance = (T)this;
  34. }
  35. void ISingleton.Destroy()
  36. {
  37. if (this.isDisposed)
  38. {
  39. return;
  40. }
  41. this.isDisposed = true;
  42. instance.Dispose();
  43. instance = null;
  44. }
  45. bool ISingleton.IsDisposed()
  46. {
  47. return this.isDisposed;
  48. }
  49. public virtual void Dispose()
  50. {
  51. }
  52. }
  53. }