| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- import { Component } from 'cc';
- /**
- * BaseSingleton
- * 轻量通用的单例基类,适用于继承自 Component 的脚本。
- * 继承后无需再编写重复的单例模板代码,只需在需要初始化时重写 init() 方法。
- */
- export abstract class BaseSingleton extends Component {
- /**
- * 子类可选的初始化函数。当首次实例化时会被调用一次。
- */
- protected init?(): void;
- /**
- * onLoad 生命周期回调,在此处完成单例实例的注册与重复节点的销毁。
- */
- protected onLoad(): void {
- // 每个继承类都会在运行时在其构造函数对象上动态创建 _instance 字段
- const ctor = this.constructor as any;
- if (!ctor._instance) {
- ctor._instance = this;
- // 首次初始化回调
- if (typeof this.init === 'function') {
- (this.init as Function).call(this);
- }
- } else if (ctor._instance !== this) {
- // 如果已经存在实例,销毁多余的节点
- this.destroy();
- }
- }
- /**
- * onDestroy 生命周期回调,用于清理单例实例。
- */
- protected onDestroy(): void {
- const ctor = this.constructor as any;
- if (ctor._instance === this) {
- ctor._instance = null;
- }
- }
- /**
- * 获取单例实例。
- */
- public static getInstance<T>(this: { _instance: T }): T {
- return this._instance;
- }
- }
|