设计模式

95 阅读1分钟

单例模式

class Singleton {
  constructor() {}
}

Singleton.getInstance = (function() {
  let instance
  return function() {
    if (!instance) {
      instance = new Singleton()
    }
    return instance
  }
})()

let s1 = Singleton.getInstance()
let s2 = Singleton.getInstance()
console.log(s1 === s2) // true

发布/订阅模式

  • 订阅者
  • 发布者
  • 信号中心

我们假定,存在一个信号中心,某个任务执行完成,就向信号中心'发布'一个信号,其他任务可以向信号中心'订阅这个信号',从而知道什么时候自己可以可以开始执行,这就叫发布/订阅模式