继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【十月打卡】第69天 前端常用的7种设计模式(5)

康遇
关注TA
已关注
手记 76
粉丝 3
获赞 9

单例模式

严格的单例模式不多,但是单例的思想随处可见

概念

什么是单例
一个对象或者实例只会被创建一次,创建后缓存起来,供全局使用

解决的问题
可以解决一个系统中只需要唯一的一个对象或者实例的场景。

代码示例以及UML类图

  • 类的静态属性或方法需要使用 static
  • 静态方法的this指向当前类
  • 静态属性或方法在UML类图中需要使用下划线

TS代码演示:

class SingleTon {
  private constructor() {}
  private static instance: SingleTon | null = null;

  static getInstance(): SingleTon {
    if (this.instance === null) {
      this.instance = new SingleTon();
    }
    return this.instance;
  }
}

const ins1 = SingleTon.getInstance();
const ins2 = SingleTon.getInstance();

console.log(ins1 === ins2);  // true

JS代码演示:

// 闭包的方式
function getInstanceGenerator() {
  let instance = null;
  class SingleTon {}

  return () => {
    if (instance === null) {
      instance = new SingleTon();
    }
    return instance;
  };
}

const getInstance = getInstanceGenerator();
const ins1 = getInstance();
const ins2 = getInstance();
console.log(ins1 === ins2); // true

// 模块的方式
let instance = null;
class SingleTon {}

export default () => {
  if (instance === null) {
    instance = new SingleTon();
  }
  return instance;
};

UML类图
图片描述

应用场景

  • 登录框、遮罩层,一个系统只有一个即可,多了没用,还浪费性能
  • Vuex、Redux的store,一个系统只能有一个,多了会出错
  • 自定义事件EventBus全局唯一
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP