设计模式 ~ 单例模式

单例模式

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

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

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

如:弹窗、遮罩层、登录框、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类图

相关推荐
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
爱敲代码的小鱼7 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
书院门前细致的苹果8 小时前
设计模式大全:单例、工厂模式、策略模式、责任链模式
设计模式·责任链模式·策略模式
铅笔侠_小龙虾9 小时前
Flutter 实战: 计算器
开发语言·javascript·flutter
大模型玩家七七9 小时前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
2501_944711439 小时前
JS 对象遍历全解析
开发语言·前端·javascript
发现一只大呆瓜10 小时前
虚拟列表:支持“向上加载”的历史消息(Vue 3 & React 双版本)
前端·javascript·面试
阔皮大师10 小时前
INote轻量文本编辑器
java·javascript·python·c#
lbb 小魔仙10 小时前
【HarmonyOS实战】React Native 表单实战:自定义 useReactHookForm 高性能验证
javascript·react native·react.js
_codemonster10 小时前
Vue的三种使用方式对比
前端·javascript·vue.js