设计模式之单例模式

13,956 阅读1分钟

案例:创建一个全局弹框组件

我们可以分为两个步骤: 1.创建弹框 2.实现单例

// 创建 弹框
function createDialog(html) {

    const div = document.createElement('div')
    div.innerHTML = html
    document.body.appendChild(div)

    return div
}

// 创建单例
function getSingle(fn) {
    let instance;
    
    // instance 存在时直接返回 不存在时赋值为fn的返回
    return function () {
        if (!instance) {
            instance = fn.apply(this, arguments)
        }
        return instance
    }
}




const bindEvent = getSingle( () => createDialog('dialog') )


const render = function () {
    console.log('开始渲染')
    bindEvent()
}

render()

render()

render()

单例模式.png

执行renden三次,只创建了一个div,实现了当前我们全局创建一个div的功能。