JS设计模式2-单例模式

92 阅读1分钟

单例模式、

定义

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

圣杯实现单例模式

喝圣水即得永生(全局变量、闭包)

const Test = (function () {
    let instance
    return function (name) {
        if (typeof instance === 'object') {
            return instance
        }
        instance = this
        this.name = name
    }
})()

const a = new Test()
Test.prototype.lastName = 'lu'
const b = new Test()
console.log(a === b, a.lastName, b.lastName)// true lu lu

封装工具函数将任意构造函数变成单例

function Test(name) {
  this.name = name
}

function getSingle(func) {
  let instance
  return function (...args) {
    if(!instance) {
      instance = new func(...args)
    }
    return instance
  }
}
const singleTest = getSingle(Test)
const a = singleTest('lusaiwen1')
Test.prototype.lastName = '34'
const b = singleTest('lusaiwen2')
Test.prototype.firstName = 'fsdfsd'
console.log(a === b, a, b) // true