如何在typescript实现单例模式且无法重复实例

399 words

💡 将 constructor 设置为 protected 或者 private,致使该类无法在外部实例化, 即可实现。

🌰 示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Single {
static instance = new this()

// `private` 或者 `protected` 皆可
private constructor() {}

echo(msg: string) {
console.log(msg)
}

static echo(msg: string) {
return this.instance.echo(msg)
}
}

❎ 错误用法

1
const single = new Single()

错误用法

✅ 正确用法

1
2
3
Single.echo('hello')
// or
Single.instance.echo('hello')

正确用法