设计模式学习(一):单例模式

单例模式的定义: 保证一个类仅有实例,并提供一个访问它的全局访问点。例如线程池、全局缓存、浏览器中的window对象等。在实际的JS开发中,也有用到,比如登陆弹窗

// 单一职责原则,singleModelMitt函数只做单例逻辑的管理
class singleModelMitt {
   constructor () {
       this.result = null
   }
   getSingle () {
       const fn = Array.prototype.shift.call(arguments)
       if (typeof fn !== 'function') {
            return alert('请传入函数类型参数')
       }
       return this.result || (this.result = fn.apply(this, arguments))
   }
}
const singleFunc = new singleModelMitt()
// 某个事件函数
function clickEvent (params) {
    document.getElementById('button').onclick = function () {
        alert(params)
    }
}
const sampleA = singleFunc.getSingle(clickEvent, [1, 2])
const sampleB = singleFunc.getSingle(clickEvent, [3, 4])

// 值为true,说明只创建了一个实例
console.log(sampleA === sampleB)
posted @ 2021-12-03 15:07  coderInside  阅读(35)  评论(0)    收藏  举报