侧边栏壁纸
博主头像
小澄科技 博主等级

行动起来,活在当下

  • 累计撰写 2 篇文章
  • 累计创建 1 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

单例模式

小澄
2025-03-14 / 0 评论 / 0 点赞 / 5 阅读 / 0 字

常规

export default class Singleton{
    private static instance: any = null
    public static getInstance<T extends {}>(this: new () => T): T {
        if(!(<any>this).instance){
            (<any>this).instance = new this();
        }
        return (<any>this).instance;
    }

    constructor() { }
}

继承cc.Component

export default class SingletonComponent<T> extends cc.Component {
  private static instance: any = null
  public static getInstance<T extends cc.Component>(this: new () => T): T {
    if ((<any>this).instance == null) {
      let newNode = new cc.Node(this.name)
      ;(<any>this).instance = newNode.addComponent(<any>this)
      cc.director.getScene().addChild(newNode)
    }
    return (<any>this).instance
  }

  onDestroy() {
    ;(<any>this).instance = null
  }
}

0

评论区