亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【十月打卡】第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 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
Web前端工程師
手記
粉絲
3
獲贊與收藏
9

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消