设计模式 ~ 单例模式

单例模式

单例模式是一种设计模式,指在确保一个类只有一个实例,并提供一个全局访问点来访问该实例;

前端对于单例模式不常用,但是单例的思想无处不在;

创建之后缓存以便继续使用;

如:弹窗、遮罩层、登录框、vuex redux 中的 store


TypeScript

禁止外部实例化:private constructor

获取单例:static getInstance

javascript 复制代码
class Singleton{
  name: string
  private constructor(name: string) {
    this.name = name
  }
  private static insatance: Human | null // 单例对象
  static getInstance(name: string): Human {
    if (Human.insatance == null) {
      Human.insatance = new Singleton(name)
    }
    return Human.insatance
  }
}

返回单例:

javascript 复制代码
const p1 = Singleton.getInstance('a')
const p2 = Singleton.getInstance('b') // 返回p1
console.log(p1 === p2) // true

JavaScript

使用闭包

javascript 复制代码
function genGetInstance() {
  let instance // 闭包
  class Singleton{}
  return () => {
    if (instance == null) {
      instance = new Singleton()
    }
    return instance
  }
}

const getInstance = genGetInstance()
const s1 = getInstance()
const s2 = getInstance()
console.log(s1 === s2) // true

模块化实现: ~ 创建单独的 js 文件

javascript 复制代码
let instance
class Singleton{}
export default () => {
    if (instance == null) {
        instance = new Singleton
    }
    return instance
}

UML类图

相关推荐
逆境不可逃4 分钟前
【从零入门23种设计模式03】创建型之建造者模式(简易版与导演版)
java·后端·学习·设计模式·职场和发展·建造者模式
henry1010101 小时前
DeepSeek生成的网页小游戏 - 迷你高尔夫
前端·javascript·游戏·html
薛一半1 小时前
React的组件
前端·javascript·react.js
薛一半2 小时前
React三大属性之props
前端·javascript·react.js
趣魂2 小时前
心跳信令通常不采用NACK机制
设计模式·软件工程·软件构建
用户5757303346242 小时前
🔥 前端必考!AJAX 数据请求全解析,async true/false 区别一次搞懂
javascript
烤麻辣烫3 小时前
正则表达式快速掌握
前端·javascript·学习·正则表达式·html
逆境不可逃3 小时前
【从零入门23种设计模式01】创建型之工厂模式(简单工厂+工厂方法+抽象工厂)
java·spring·设计模式·简单工厂模式·工厂方法模式·抽象工厂模式·工厂模式
心之语歌4 小时前
flutter 父子组件互相调用方法,值更新
前端·javascript·flutter
肖。35487870944 小时前
html中onclick误区,后续变量会更改怎么办?
android·java·javascript·css·html