JS设计模式之单列模式详解

单例模式

  • 什么是单例模式呢?
  • 我们都知道,构造函数可以创造一个对象
  • 我们 new 很多次构造函数就能得到很多的对象
  • 单例模式: 就是使用构造函数实例化的时候,不管实例化多少回,都是同一个对象
    • 也就是一个构造函数一生只能 new 出一个对象
  • 也就是说,当我们使用构造函数,每一次 new 出来的对象 属性/功能/方法 完全一样 的时候,我们把他设计成单例模式
    - 核心代码
  • 单例模式的核心代码很简单
  • 其实就是判断一下,他曾经有没有 new 出来过对象
  • 如果有,就还继续使用之前的那个对象,如果没有,那么就给你 new 一个
在这里插入代码片
// 准备一个构造函数
// 将来要 new 的
function Person() {}

// 准备一个单例模式函数
// 这个单例模式函数要把 Person 做成一个单例模式
// 将来再想要 new Person 的时候只要执行这个 singleton 函数就可以了
let instance
function singleton () {
  
  if (!instance) { // 如果 instance 没有内容
    // 来到这里,证明 instance 没有内容
    // 给他赋值为 new Person
      instance = new Person()
  }
  
  // 返回的永远都是第一次 new Person 的实例
  // 也就是永远都是一个实例
  return instance
}

const p1 = singleton()
const p2 = singleton()
console.log(p1 === p2) // true

单列模式应用
我们就用这个核心代码简单书写一个 demo

在这里插入代码片
// 这个构造函数的功能就是创建一个 div,添加到页面中
function CreateDiv() {
    this.div = document.createElement('div')
    document.body.appendChild(this.div)
}

CreateDiv.prototype.init = function (text) {
    this.div.innerHTML = text
}

// 准备把这个 CreateDiv 做成单例模式
// 让 singleton 成为一个闭包函数
const singleton = (function () {

    let instance

    return function (text) {
        if (!instance) {
            instance = new CreateDiv()
        }
        instance.init(text)
        return instance
    }
})()

singleton('hello') // 第一次的时候,页面中会出现一个新的 div ,内容是 hello
singleton('world') // 第二次的时候,不会出现新的 div,而是原先的 div 内容变成了 world
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值