Singleton.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. namespace ET
  3. {
  4. public interface ISingleton: IDisposable
  5. {
  6. void Register();
  7. void Destroy();
  8. bool IsDisposed();
  9. }
  10. public abstract class Singleton<T>: ISingleton where T: Singleton<T>, new()
  11. {
  12. private bool isDisposed;
  13. [StaticField]
  14. private static T instance;
  15. public static T Instance
  16. {
  17. get
  18. {
  19. return instance;
  20. }
  21. }
  22. void ISingleton.Register()
  23. {
  24. if (instance != null)
  25. {
  26. throw new Exception($"singleton register twice! {typeof (T).Name}");
  27. }
  28. instance = (T)this;
  29. }
  30. void ISingleton.Destroy()
  31. {
  32. if (this.isDisposed)
  33. {
  34. return;
  35. }
  36. this.isDisposed = true;
  37. instance.Dispose();
  38. instance = null;
  39. }
  40. bool ISingleton.IsDisposed()
  41. {
  42. return this.isDisposed;
  43. }
  44. public virtual void Dispose()
  45. {
  46. }
  47. }
  48. }