Singleton.ts 492 B

123456789101112131415161718192021
  1. import { _decorator, Component, Node } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. type SingletonConstructor<T> = {
  4. new (...args: any[]): T;
  5. }
  6. export class Singleton {
  7. private static instances: Map<Function, any> = new Map();
  8. private constructor() {}
  9. public static getInstance<T>(cls: SingletonConstructor<T>): T {
  10. if (!this.instances.has(cls)) {
  11. this.instances.set(cls, new cls());
  12. }
  13. return this.instances.get(cls);
  14. }
  15. }