[TypeScript][CocosCreator]泛型单例

/**
 * Ts's singleton is too ugly.so i will not use it.
 */
export class Singleton<T>{
    private static instance: any = null;
    public static Instance<T>(c: { new(): T }): T {
        if (this.instance == null) {
            this.instance = new c();
        }
        return this.instance;
    }

    public Update(dt: number) {

    }
}

还需要把类传入,用于构造函数生成instance,感觉很不友好啊。

使用示例

Animal.ts

import { Singleton } from "./Singleton";

export class Animal extends Singleton {
    public root: string = "animal";
}

Beast.ts

import { Animal } from "./Animar";

export class Beast extends Animal {
    public name = "beast 1";
    constructor() {
        super();
        this.root = "i am a beast";
    }
}

Bird.ts

import { Animal } from "./Animar";

export class Bird extends Animal {
    public name: string = "bird 1";
    constructor(){
        super();
        this.root="i am a bird";
    }
}

使用

    let bird = Bird.Instance(Bird);
    let beast = Beast.Instance(Beast);

    Debug.Log(bird.root);
    Debug.Log(bird.name);
    Debug.Log(beast.root);
    Debug.Log(beast.name);

打印结果:
在这里插入图片描述

你可能感兴趣的:(CocosCreator,TypeScript)