单例模式

52 阅读1分钟

单例模式

js
    设计模式: 是为了解决某一类问题的最优解
    
    单例模式
         创建一个类,这个类的一生只能有一个实例化对象
    完成思路:
        首先要有一个 class 
        在每次准备实例化这个  类 之前,先判断之前有没有对这个 类 进行过实例化
        如果进行过,那么我们不在进行新的实例化,而是拿到之前的实例化对象
        如果没有进行过,那么我们这时候开始进行一个实例化
js
    <script>
        const Dialog = ((instance) => {
            class Dialog{
                constructor() {
                    this.name = '张三'
                }

                setName(newName) {
                    this.name = newName
                }
            }

            return (name) => {
                if(instance === null){
                    instance = new Dialog()
                }
                instance.setName(name)
                return instance
            }
        })(null)

        const d1 = Dialog('第一次')
        console.log(d1)  // Dialog {name: '第一次'}

        const d2 = Dialog('第二次')
        console.log(d2)  // Dialog {name: '第二次'}

        const d3 = Dialog('第三次')
        console.log(d3)  // Dialog {name: '第三次'}

        console.log(d1 === d2) // true
        console.log(d2 === d3) // true
    </script>