首页 > 其他 > 详细

设计模式-单例模式

时间:2019-01-22 21:27:23      阅读:165      评论:0      收藏:0      [点我收藏+]
        class Test{//只需要new 一次 并且在内部完成
            constructor(name){
                this.name = name
            }
            showName(){
                alert(`name: ${this.name}`)
            }
        }

        Test.aa = (function(){//定义一个静态方法 在内部new 出上面的实例
            let a
            return function(){
                if(!a){
                    a = new Test('chenchen')
                }
                return a
            }
        })()

        let obj1 = Test.aa()
        obj1.showName()

        let obj2 = Test.aa()
        obj2.showName()

        console.log('obj1 === obj2:', obj1 === obj2 )//true 

        console.log('----分割线----')

        let obj3 = new Test('chengcheng')
        obj3.showName()

        console.log('obj1 === obj3:', obj1 === obj3 ) //false 多次new出来的实例对象不等

设计模式-单例模式

原文:https://www.cnblogs.com/yzyh/p/10305925.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!