1、单例模式

55 阅读1分钟

核心:确保一个类只有一个实例,并提供一个全局访问点

场景:状态管理、路由对象都是只有一个实例的

代码实现:

普通版本

function Father(name) {
  if(Father.instance) return Father.instance
  
  this.name = name  

  Father.instance = this
}

const f1 = new Father('xx')
const f2 = new Father('yy')

f1 === f2 // true

友好版本

const createSingle = function(fn) {
  let instance;

  return function(...args) {
    return instance || (instance = new fn(...args))
  }
}

function Father(name, age) {
  this.name = name
  this.age = age
}

const createSingleFather = createSingle(Father)

const f1 = new createSingleFather('xx', 45)
const f2 = createSingleFather('yy', 49)

f1 === f2 // true

总结:多次调用函数,想办法永远只产生一个实例就行