单例模式

1.什么是单例模式

单例模式,单是一个的意思,例是实例化对象的意思。 单例模式,保证一个类仅有一个实例,并提供一个访问该对象的全局方法。

2.单例模式的应用

vuex以及Redux都使用单例模式来实现,全局使用一个实例进行维护,多个组件之间可以共享一份数据。

2.1 命名空间

采用命名空间可以有效减少命名冲突以及全局变量的个数,其本质是通过字面量的形式创建对象。

先考虑下面一种情况:

// A程序员的JS代码
function add(){
    console.log(123);
}
// B程序员的JS代码
var add=12;
// A程序员重新开始维护
add();
// 进行报错
Uncaught TypeError: add i

以上的这种情况是多人维护一份代码存在的潜在隐患,为了避免命名冲突,需要单独创建命名空间。

let a={
   add:function(){
       console.log(123);
   }
}
let devB = {
  add: ''
}

a.add();

如此一来,A和B的代码彼此之间不会影响。

2.2 管理模块

在代码中,我们会使用到许多模块,为了更加清晰地区分不同模块,我们可以使用单例模式将模块管理起来。

2.3 弹窗的实现

在使用弹窗的过程中,我们可以发现,弹窗会有一个visible来控制

3.如何实现单例模式

思路:使用变量存储当前的实例,在获取这个类的实例之前,判断一下实例是否存在,如果存在直接返回。

3.1 ES6实现单例模式

ES6中通过class以及constructor来实例化对象。 class是一个抽象的定义,是一类具有相同属性以及行为的抽象,对象则是在类的定义上,完成多样性的建设。

class SingletonFunc {
  constructor(name) {
    //首次使用构造器实例
    if (!SingletonFunc.instance) {
      this.name = name;
      SingletonFunc.instance = this;
    }
    return SingletonFunc.instance;
  }
}

let company = new SingletonFunc('公司');
let apple = new SingletonFunc('苹果');

console.log(company === apple);  //true

3.2 ES6优化

使用static可以不用new初始化,直接通过类就可以直接访问对应的属性以及方法。

class SingletonFunc {
  constructor(name) {
    //首次使用构造器实例
    if (!SingletonFunc.instance) {
      this.name = name;
      SingletonFunc.instance = this;
    }
    return SingletonFunc.instance;
  }
  static getInstance(name){
      if(!this.instance){
          this.instance = new SingletonFunc(name);
      }
      return this.instance;
  }
}
let company = SingletonFunc.getInstance('公司');
let apple = SingletonFunc.getInstance('苹果');

console.log(company === apple);  //true

4.总结

单例模式的核心是确保只有一个实例, 并提供全局访问。 就像我们只需要一个浏览器的window对象, jQuery的$对象而不再需要第二个。

export default new youclassName(),就已经满足了单例模式,能够保证