[TypeScript][CocosCreator]泛型单例

it2022-05-06  12

/** * 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<T> extends Singleton<T> { public root: string = "animal"; }

Beast.ts

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

Bird.ts

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

使用

let bird = Bird.Instance<Bird>(Bird); let beast = Beast.Instance(Beast); Debug.Log(bird.root); Debug.Log(bird.name); Debug.Log(beast.root); Debug.Log(beast.name);

打印结果:


最新回复(0)