学习JavaScript 设计模式 - 单例模式

447 阅读2分钟

介绍

单例模式属于创建型模式,它提供了一种创建对象的最佳方式。 为了解决一个对象频繁的创建和销毁问题, 保证系统只有唯一实例对象, 提高性能, 节约资源。

class Dialog {
    static instance = null;
    
    static getInstance() {
         //判断是否已经有这个单例,如果有则返回,如果没有则创建。
         if (Dialog.instance === null) {
             Dialog.instance = new Dialog()
         }
         
         //给其它对象提供这个实例
         return Dialog.instance
    }
}

就这几行代码就完成最简单的单例模式

特性

  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。
  • 单例类必须给所有其他对象提供这一实例。

技巧

先判断实例是否存在, 如果存在则直接返回, 如果不存在则创建再返回

下面用具体场景代码重写下(这里我以弹窗为例,封装一个弹窗组件), 这个模式虽然很简单,但是我感觉很多文章写的都有问题...

场景

比如 弹窗、桌面端程序(如QQ音乐)等, 多次点击都只会出现一个实例, 都是经典的单例用武之地。

class Dialog {
    static instance = null;

    constructor() {
        this.create()
    }
    create(component='') { //这里我只做了个弹窗盒子, 具体内容可以通过封装组件,传进来
        //设置弹窗样式
        const dom = document.createElement('div')
        dom.id = "my-form"
        dom.style.zIndex = '999'
        dom.style.width = '600px'
        dom.style.height = '300px'
        dom.style.background = '#fff'
        dom.style.color = 'red'

        dom.innerHtml = component || '我是弹窗'

        document.body.appendChild(dom)
    }

    getDom() {
        return document.getElementById('my-form')
    }

    static getInstance() {
        if (Dialog.instance === null) {
            Dialog.instance = new Dialog()
        }
        return Dialog.instance
    }

    open() {
        this.getDom().style.display = 'block'
    }

    close() {
        this.getDom().style.display = 'none'
    }
}

接下来时候页面添加一个按钮操作就可以了

<el-button @click="openEvent">查看详情</el-button>

openEvent() {
    Dialog.getInstance().open()
}

同样道理, 关闭弹窗也很简单

<el-button @click="closeEvent">关闭</el-button>

closeEvent() {
    Dialog.getInstance().close()
}

重点检查两个问题:

  • 初始化重复创建 dom 或者 还没点击就先创建dom
  • 点击弹窗重复添加 dom

这两点是很多新手常犯错误

单例弹窗.gif

最后的轻语

婚恋拇指法则:

生理上有冲动, 精神上受鼓舞, 沟通上很流畅