Singleton.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //==================================================================================
  2. //==================================================================================
  3. //----------------------------------------------------------------------------
  4. //----------------------------------------------------------------------------
  5. using UnityEngine;
  6. /// 单件类,非MonoBehaviour类型继承(线程安全)
  7. /// @单件实例必须在代码中显式创建, GetInstance()不创建实例
  8. /// @bhy
  9. /// @2019.01.03
  10. /// 非MonoBehaviour类型的单件辅助基类,利用C#的语法性质简化单件类的定义和使用
  11. /// @T : 单件子类型
  12. public class Singleton<T> where T : class, new()
  13. {
  14. //单件子类实例
  15. private static T s_instance;
  16. protected Singleton()
  17. {
  18. }
  19. //--------------------------------------
  20. /// 创建单件实例
  21. //--------------------------------------
  22. public static void CreateInstance()
  23. {
  24. if (s_instance == null)
  25. {
  26. s_instance = new T();
  27. (s_instance as Singleton<T>).Init();
  28. }
  29. }
  30. //--------------------------------------
  31. /// 删除单件实例
  32. //--------------------------------------
  33. public static void DestroyInstance()
  34. {
  35. if (s_instance != null)
  36. {
  37. (s_instance as Singleton<T>).UnInit();
  38. s_instance = null;
  39. }
  40. }
  41. public static T Instance
  42. {
  43. get
  44. {
  45. if (s_instance == null)
  46. {
  47. CreateInstance();
  48. }
  49. return s_instance;
  50. }
  51. }
  52. //--------------------------------------
  53. /// 返回单件实例
  54. //--------------------------------------
  55. public static T GetInstance()
  56. {
  57. if (s_instance == null)
  58. {
  59. CreateInstance();
  60. }
  61. return s_instance;
  62. }
  63. //--------------------------------------
  64. /// 是否被实例化
  65. //--------------------------------------
  66. public static bool HasInstance()
  67. {
  68. return (s_instance != null);
  69. }
  70. //--------------------------------------
  71. /// 初始化
  72. /// @需要在派生类中实现
  73. //--------------------------------------
  74. public virtual void Init()
  75. {
  76. }
  77. //--------------------------------------
  78. /// 反初始化
  79. /// @需要在派生类中实现
  80. //--------------------------------------
  81. public virtual void UnInit()
  82. {
  83. }
  84. }