定义

一个类仅有一个实例,并提供一个范文她的全局访问点(静态放方法)

优缺点

优点
减少开销(内存、系统性能。。。);优化和共享资源访问
缺点
扩展困难;对测试不利;与单一职责原则冲突

应用场景

需要频繁的进行创建和销毁的对象、创建对象耗时和好资源过多但又经常用到

角色

singleton:单例

类图

image.png

懒汉式

  1. class Singleton{
  2. private constructor(){}
  3. private static instance:Singleton = new Singleton()
  4. public static getInstance():Singleton{
  5. return this.instance;
  6. }
  7. }
  8. console.log(Singleton1.getInstance(), '11111');

饿汉式

  1. class Singleton {
  2. private constructor(){}
  3. private static instance: Singleton = null;
  4. public static getInstance() : Singleton {
  5. if (this.instance === null) {
  6. this.instance = new Singleton();
  7. }
  8. return this.instance;
  9. }
  10. }
  11. console.log(Singleton.getInstance(), '2222')