【发布时间】: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