单例模式: 保证一个类只有一个实例,一般先判断实例是否存在,如果存在直接返回,不存在则先创建再返回,这样就可以保证一个类只有一个实例对象。

作用:

(1)、保证某个类的对象的唯一性;

(2)、模块间通信;

(3)、防止变量污染

 1 function Singleton(name) {
 2        this.name = name;
 3        this.instance = null;
 4   }
 5 Singleton.prototype.getName = function () {
 6         console.log(this.name, 1)
 7  }
 8  Singleton.getInstance = function (name) {
 9     if (!this.instance) {
10           this.instance = new Singleton(name);
11         }
12            return this.instance;
13      }
14   var a = Singleton.getInstance('sven1');
15   var b = Singleton.getInstance('sven2');
16   // 指向的是唯一实例化的对象
17   console.log(a === b, a.getName());

 

es6实现

 1 class Demo1{
 2     private static instance:Demo1;
 3     private constructor(public name:string){}
 4     static getInstance(name:string){
 5         if(!this.instance){
 6             this.instance=new Demo1(name)
 7         }
 8         return this.instance
 9     }
10 }
11 const d1=Demo1.getInstance('')
12 const d2=Demo1.getInstance('')
13 console.log(d1,d2,d1==d2)
14 //小 小 true 
15 // 指向的是唯一实例化的对象

 

posted on 2020-06-18 11:54  小白学前端  阅读(182)  评论(0编辑  收藏  举报