设计模式之单例模式

定义

保证一个类,仅有一个实例,并提供一个访问它的全局访问点。

方法

方法一:此方法有弊端,Test.instance挂在全局,能修改,不符合开闭原则

        function Test(name) {
            if (typeof Test.instance == 'object') {
                return Test.instance
            }
            this.name = name;
            Test.instance = this;
        }
        var a = new Test('a')
        var b = new Test('a')
        console.log(a == b) // true

方法二:利用闭包思想,但是还是有弊端,new出来的对象,它的构造函数constructor并不是Test,如果要在原型prototype加方法的话,new出来的对象并不能调用

        function Test(name) {
            var instance = this;
            this.name = name;
            Test = function () {
                return instance
            }
        }

        var a = new Test('a')
        var b = new Test('a')

        console.log(a == b) //true

方法三:完美单例模式

        var Test = (function(){
            var instance = null;
            return function(name){
                if(instance){
                    return instance
                }
                this.name = name
                instance = this
            }
        })()

        var a = new Test('a')
        var b = new Test('a')
        
        console.log(a == b) //true

运用

说了这么多我们在事件中运用一下,在html创建一个按钮,让它无论点击多少次都只出现一个弹窗(只是一个比喻)

        var creat = (function(text){
            var div = null
            return function(text){
                if(div){
                    return div
                }
                div = document.createElement('div')
                div.innerText = text;
                div.style.display = 'none';
                document.body.appendChild(div);
                return  div  
            }
        })()

        btn.onclick = function(){
            var div = creat('我是谁,我在哪')
            div.style.display = 'block'
        }

其实上面这个方法看起来还是不够高级,下面我们写一个更高级的方法,并调用它

        var single = function (fn) {
            var res = null;
            return function () {
                if (!res) {
                    res = fn.apply(this, arguments)
                }
                return res
            }
        } //单例模式高级方法

        var creat = function (text) {
            var div = document.createElement('div')
            div.innerText = text;
            div.style.display = 'none';
            document.body.appendChild(div);
            return div
        } // 创建弹窗

        var fn = single(creat)  //调用单例模式函数 

        btn.onclick = function () {
            var div = fn('我是谁,我在哪')
            div.style.display = 'block'
        }

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值