设计模式 ~ 单例模式

单例模式

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

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

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

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

相关推荐
LoveXming2 小时前
Chapter14—中介者模式
c++·microsoft·设计模式·中介者模式·开闭原则
崎岖Qiu4 小时前
【设计模式笔记06】:单一职责原则
java·笔记·设计模式·单一职责原则
Yeniden4 小时前
【设计模式】适配器模式大白话讲解!
设计模式·适配器模式
孤狼warrior5 小时前
爬虫进阶 JS逆向基础超详细,解锁加密数据
javascript·爬虫
前端炒粉5 小时前
18.矩阵置零(原地算法)
javascript·线性代数·算法·矩阵
listhi5205 小时前
利用React Hooks简化状态管理
前端·javascript·react.js
华仔啊6 小时前
这个Vue3旋转菜单组件让项目颜值提升200%!支持多种主题,拿来即用
前端·javascript·css
CsharpDev-奶豆哥7 小时前
JavaScript性能优化实战大纲
开发语言·javascript·性能优化
金色熊族8 小时前
装饰器模式(c++版)
开发语言·c++·设计模式·装饰器模式
yume_sibai10 小时前
TS 常用内置方法
前端·javascript·typescript