为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
设计模式

单例模式

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

概念

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

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

代码示例以及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全局唯一
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消