【问题标题】:Can be inherit singleton class in typescript?可以在打字稿中继承单例类吗?
【发布时间】:2020-01-02 19:02:38
【问题描述】:

我需要继承单例类并覆盖它的方法。打字稿有可能吗?或在打字稿中实现此类场景的任何其他方式。

// 父类

export class SFSCommands {
    static instance: SFSCommands;
    protected constructor() {
        if (SFSCommands.instance) {
            return SFSCommands.instance;
        }

        setInterval(() => {
            this.initSfsCommands('sss');
        }, 2000);
    }

    static getInstance() {
        if (!SFSCommands.instance) {
            SFSCommands.instance = new SFSCommands();
        }
        return SFSCommands.instance;
    }

    initSfsCommands(e: any) {
        console.log('comming in service');
    }
}

//**** 子类 ***********

import { SFSCommands } from '../utility/sfscommands';

export abstract class GameModel extends SFSCommands {
    roomName: string;

    constructor() {
        super();
        console.log(this);
    }

    // called from child whien game component inisilized

    initSfsCommands(event: any) {
        console.log('game model');
    }

}

我从我的 app.component.ts 文件中调用 SFSCommands.getInstance()

【问题讨论】:

  • 试用过的代码会更有帮助!
  • 单例类是什么意思?
  • @Ludevik 单例类意味着我们只初始化了一次类内存,之后我们共享同一个实例。
  • 所以您的意思是在根模块中提供的单例服务,并且您只想覆盖该服务的一种方法,对吧?

标签: typescript singleton


【解决方案1】:

Angular 可注入/服务类是单例。

@Injectable({providedIn: 'root'})
export class GlobalService {}

它会在你第一次注入组件时被实例化。

constructor(private globalService: GlobalService){}

【讨论】:

  • 感谢@Carsten,但我也需要方法覆盖。
【解决方案2】:

这不是很好,但有可能

export class GameModel extends SFSCommands {
  static getInstance() {
    super.getInstance().initSfsCommands = (event: any) => {
      console.log('game model');
    }
    return GameModel.instance;
  }
}

你应该打电话给GameModel.getInstance()而不是SFSCommands.getInstance()

希望有帮助

【讨论】:

  • 你能解释更多吗?
  • 当您从 SFSCommands 调用 getInstance() 时,您构建的是 SFSCommands,而不是 GameModel。 SFSCommands 永远不会知道 GameModel 的存在。因此它无法知道来自 GameModel 的 initSfsCommands。
  • 所以你需要重写函数而不是等待GameModel中的函数被调用。这就是为什么我们有super.getInstance().initSfsCommands = (event: any) => { console.log('game model'); }
  • 但是我说它不好,因为它完全重写了 SFSCommands 的函数。这意味着即使稍后您调用 SFSCommands.getInstall,它也会调用新函数
猜你喜欢
  • 1970-01-01
  • 2017-12-04
  • 2020-05-07
  • 1970-01-01
  • 2017-07-14
  • 2016-12-05
  • 2021-02-14
  • 2017-04-10
  • 2021-04-26
相关资源
最近更新 更多