【问题标题】:What is the purpose of a `getInstance()` method?`getInstance()` 方法的目的是什么?
【发布时间】:2021-11-03 17:25:34
【问题描述】:

我在看一个用户服务,我的理解是它类似于 Nest 中的用户服务,但不是真的。

在其中我看到以下内容:

export class UsersService {
  private usersDao: UsersDao

  constructor() {
     this.usersDao = UsersDao.getInstance();
  }
}

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

getInstance() 到底在做什么?为什么不只是:

export class UsersService {

  constructor(private usersDao: UsersDao) {}
}

getInstance()的目标是什么?

【问题讨论】:

  • 代码使用Singleton pattern来限制代码创建的实例数
  • static getInstance(): UsersService 方法定义似乎存在于任何class 之外。能否提供完整的代码?
  • 你说的是UsersDao.getInstance()还是另一个(大概是UsersService.getInstance)?
  • @blurfus …这甚至不是一个合适的单例模式,因为每个人仍然可以做到new UsersService();
  • @Daniel,不,我的意思是构造函数本身可以标记为私有 - 即 private contructor() {...} - 请参阅 stackoverflow.com/a/40034649/600486 以获取完整示例

标签: javascript typescript singleton


【解决方案1】:

通常这是单例模式的一部分。基本上是一个类,一旦实例化,任何后续类都将引用该实例,而不是每次都创建一个新实例。

https://en.wikipedia.org/wiki/Singleton_pattern

它对于第一次构造时需要发生复杂事情的类很有用,但所有后续调用只需要访问属性。

我还想提一下,您可以(特别是在 JavaScript 中)export 一个实例,以及所有modules that import the module will have access to the same instance

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多