设计模式 ~ 单例模式

单例模式

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

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

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

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

相关推荐
一直在学习的小白~20 分钟前
node_modules 明明写进 .gitignore,却还是被 push/commit 的情况
前端·javascript·vue.js
nightunderblackcat1 小时前
新手向:从零理解LTP中文文本处理
前端·javascript·easyui
User:你的影子1 小时前
WPF ItemsControl 绑定
开发语言·前端·javascript
库奇噜啦呼1 小时前
【iOS】单例模式
ios·单例模式
馨谙1 小时前
设计模式之单例模式大全---java实现
java·单例模式·设计模式
知识分享小能手2 小时前
React学习教程,从入门到精通,React 构造函数(Constructor)完整语法知识点与案例详解(16)
前端·javascript·学习·react.js·架构·前端框架·vue
召摇2 小时前
NodeBB 深度解析:现代论坛系统的架构设计与实践指南
前端·javascript
flower_tomb3 小时前
对浏览器事件机制的理解
前端·javascript·vue.js
超人不会飛3 小时前
仿豆包 H5应用核心模板:用Vue快速复刻大模型对话体验
前端·javascript·vue.js
程序张3 小时前
Vue3+Vite 现代化前端框架👊打破 Chrome 83 内核限制
前端·javascript·vue.js