单例模式

50 阅读1分钟

1.设计模式

为了解决 某一类问题 的一个优化过的代码解决方案

单例模式:

一个构造函数, 一生只能创建一个实例化对象

准备一个变量默认赋值为 null, 然后再第一次实例化的时候 给这变量赋值为实例化对象

后续在调用实例化的时候, 就不再创建实例化对象了, 而是拿到提前准备好的变量

        class Dialog {
            constructor() {
                console.log('在页面中 创建了 一个 弹出层')
            }
        }

        let instance = null
        function newDialog() {
            if (instance === null) {
                instance = new Dialog()
            }

            return instance
        }

        // 第一次调用, 创建一个实例化对象然后给到 instance 中, 并返回 instance
        let d1 = newDialog()

        // 第二次以及后续的所有调用, 都是直接返回 instance
        let d2 = newDialog()
        newDialog()
        newDialog()
        newDialog()
        newDialog()

单例模式升级

        class Dialog {
            constructor() {
                console.log('在页面中 创建了 一个 弹出层')
            }
        }

        /**
         *  升级1: 原本的 instance 变量为一个全局变量, 本次利用自执行函数与闭包将其修改为了 局部变量
        */
        const newDialog = (function () {
            // 自执行函数内 创建一个变量(局部变量)
            let instance = null
            return function () {
                if (instance === null) {
                    instance = new Dialog()
                }
                return instance
            }
        })()

        const d1 = newDialog()
        const d2 = newDialog()
         const Dialog = (function () {
            let instance = null

            class Dialog {
                constructor() {
                    this.title = ''
                    console.log('在页面中 创建了 一个 弹出层')
                }
                setTitle(newTitle) {
                    this.title = newTitle
                }
            }

            return function (type) {
                if (instance === null) {
                    // 当前分支语句的代码 只会在第一次的时候 执行
                    instance = new Dialog()
                }

                // 此时的位置, 每一次调用 newDialog 都会执行一次
                instance.setTitle(type)

                return instance
            }
        })()

        const d1 = new Dialog('警告')
        console.log(d1)

        // 过了很久之后, 第二次调用
        const d2 = new Dialog('通用')
        console.log(d2)