Instance.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**单例
  2. * 加方法型
  3. * public static getInstance(): XXX{
  4. return Instance.get(XXX);
  5. }
  6. */
  7. export default class Instance {
  8. public static get<T>(clazz:new (...param: any[]) => T, ...param: any[]): T {
  9. if (clazz["__Instance__"] == null) {
  10. clazz["__Instance__"] = new clazz(...param);
  11. }
  12. return clazz["__Instance__"];
  13. }
  14. }
  15. /**单例
  16. * 继承型,静止实例化
  17. */
  18. export class Singleton {
  19. // 实例
  20. private static _instance: Singleton;
  21. // 是否是通过getInstance实例化
  22. private static _instantiateByGetInstance: boolean = false;
  23. /**
  24. * 获取实例
  25. */
  26. public static getInstance<T extends Singleton>(this: (new () => T) | typeof Singleton): T {
  27. const _class = this as typeof Singleton;
  28. if (!_class._instance) {
  29. _class._instantiateByGetInstance = true;
  30. _class._instance = new _class();
  31. _class._instantiateByGetInstance = false;
  32. }
  33. return _class._instance as T;
  34. }
  35. /**
  36. * 构造函数
  37. * @protected
  38. */
  39. protected constructor() {
  40. if (!(this.constructor as typeof Singleton)._instantiateByGetInstance) {
  41. throw new Error("Singleton class can't be instantiated more than once.");
  42. }
  43. }
  44. }