前端中的设计模式——单例模式

  1. 什么是单例模式:

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

  2. 为什么需要单例模式:

    • 为了将“描述同一件事务的属性或者特征归纳汇总在一起”,同时避免全局变量污染.
    • 模块化开发之间数据的共享.(状态管理)
  3. 单例模式的优点:

    • 对于频繁使用的对象,可以省略创建对象所花费的时间.
    • 由于 new 操作的次数减少,对系统内存的使用频率也会降低.
    • 全局唯一性,可以保证全局数据和功能的共享.
  4. 常见的单例模式:

    • 浏览器中的window对象
    • 类库中的全局对象,例如Vuex、Redux
    • 小程序中的App对象.(getApp()方法其实就是获取唯一的App实例)
  5. 单例模式的实现:

    class God {
      constructor() {
        this.instance = null;
        this.human = [];
      }
    
      static getInstance() {
        const { instance } = this;
        this.instance =  instance ? instance : new God();
        return this.instance;
      }
    
      create(item) {
        this.human.push(item);
      }
    }
    
  6. 纯净的单例模式:

    class God {
    
      static instance = null;
    
      constructor() {
        let { instance } = God;
        this.human = [];
        instance =  instance ? instance : this;
        return instance;
      }
    
      create(item) {
        this.human.push(item);
      }
    }
    
  7. 应用场景:

    • 简单的全局数据共享(小程序实例)
    • 完整源代码

你可能感兴趣的:(设计模式,前端技术,设计模式,js,es6/es7)