BaseSingleton.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { Component } from 'cc';
  2. /**
  3. * BaseSingleton
  4. * 轻量通用的单例基类,适用于继承自 Component 的脚本。
  5. * 继承后无需再编写重复的单例模板代码,只需在需要初始化时重写 init() 方法。
  6. */
  7. export abstract class BaseSingleton extends Component {
  8. /**
  9. * 子类可选的初始化函数。当首次实例化时会被调用一次。
  10. */
  11. protected init?(): void;
  12. /**
  13. * onLoad 生命周期回调,在此处完成单例实例的注册与重复节点的销毁。
  14. */
  15. protected onLoad(): void {
  16. // 每个继承类都会在运行时在其构造函数对象上动态创建 _instance 字段
  17. const ctor = this.constructor as any;
  18. if (!ctor._instance) {
  19. ctor._instance = this;
  20. // 首次初始化回调
  21. if (typeof this.init === 'function') {
  22. (this.init as Function).call(this);
  23. }
  24. } else if (ctor._instance !== this) {
  25. // 如果已经存在实例,销毁多余的节点
  26. this.destroy();
  27. }
  28. }
  29. /**
  30. * onDestroy 生命周期回调,用于清理单例实例。
  31. */
  32. protected onDestroy(): void {
  33. const ctor = this.constructor as any;
  34. if (ctor._instance === this) {
  35. ctor._instance = null;
  36. }
  37. }
  38. /**
  39. * 获取单例实例。
  40. */
  41. public static getInstance<T>(this: { _instance: T }): T {
  42. return this._instance;
  43. }
  44. }