设计模式 ~ 单例模式

单例模式

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

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

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

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

相关推荐
@yanyu66614 小时前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
@大迁世界14 小时前
2026年React大洗牌:React Hooks 将迎来重大升级
前端·javascript·react.js·前端框架·ecmascript
Momentary_SixthSense14 小时前
设计模式之工厂模式
java·开发语言·设计模式
Java码农也是农14 小时前
Multi-Agent 系统设计模式
设计模式·agent·multi-agent
sg_knight14 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
风止何安啊14 小时前
为什么要有 TypeScript?让 JS 告别 “薛定谔的 Bug”
前端·javascript·面试
海天鹰15 小时前
SOC架构
javascript
前进的李工16 小时前
MySQL角色管理:权限控制全攻略
前端·javascript·数据库·mysql
NPE~16 小时前
[App逆向]环境搭建下篇 — — 逆向源码+hook实战
android·javascript·python·教程·逆向·hook·逆向分析
洒满阳光的庄园16 小时前
Electron 桌面端打包流程说明
前端·javascript·electron