设计模式 ~ 单例模式

单例模式

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

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

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

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

相关推荐
Jenlybein3 小时前
快速了解熟悉 Vite ,即刻上手使用
前端·javascript·vite
Ailrid3 小时前
@virid/core:用游戏引擎的思维来写应用-高度确定性的应用开发引擎
javascript
SuperEugene5 小时前
Vue3 组件复用设计:Props / 插槽 / 组合式函数,三种复用方式选型|组件化设计基础篇
前端·javascript·vue.js
nFBD29OFC6 小时前
利用Vue元素指令自动合并tailwind类名
前端·javascript·vue.js
zk_one8 小时前
【无标题】
开发语言·前端·javascript
AIBox3659 小时前
openclaw api 配置排查与接入指南:网关启动、配置文件和模型接入全流程
javascript·人工智能·gpt
precious。。。9 小时前
1.2.1 三角不等式演示
前端·javascript·html
阿珊和她的猫9 小时前
TypeScript 中的 `extends` 条件类型:定义与应用
javascript·typescript·状态模式
众创岛9 小时前
iframe的属性获取
开发语言·javascript·ecmascript
echome88810 小时前
JavaScript Promise 与 async/await 实战:5 个高频异步编程场景的优雅解决方案
开发语言·javascript·ecmascript