描述:一个类只有一个实例
优点:减少内存,共享访问
缺点:不宜扩展和测试
应用:用于需要频繁创建的对象
两种实现
classDiagram
class Singleton {
-constructor()
-getInstance
+getInstance()
}
1 2 3 4 5 6 7 8 9 10 11 12
| class Singleton { private constructor(){} private static instance : Singleton = new Singleton(); public static getInstance() : Singleton { return this.instance; } } console.log(Singleton.getInstance(), '11111');
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Singleton { private constructor(){} private static instance: Singleton = null; public static getInstance() : Singleton { if (this.instance === null) { this.instance = new Singleton(); } return this.instance; } } console.log(Singleton.getInstance(), '2222')
|