设计模式 javascipt - singleton 单例模式实现

时间:2021-06-02 14:36:57   收藏:0   阅读:0

//1. ES5 闭包实现单例模式

        let singleton = (function(){
            let instance = null;

            return function(name){
                this.name = name;

                instance = instance? instance : this;
                return instance;
            }
        })();

        singleton.prototype.getName = function(){
            return this.name;
        }
        let w = new singleton("hello");
        console.log(w.getName());

        let m = new singleton("nihao")
        console.log(m.getName());


// 2. ES6 实现单例模式
   
     class singleton {
         constructor(name){
             this.name = name;
         }
         
         static getInstance(name){
             if(!this.instance){
                 this.instance = new singleton(name);
             }

             return this.instance;
         }
      }

      let w = singleton.getInstance("hello");
      console.log(w.name);

      let m = singleton.getInstance("nihao")
      console.log(m.name);



评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!