JavaScript 设计模式之单例模式

单例模式

常规单例

 单例模式我们在日常使用中还是非常多的,比如常见的 jQuery,prototype,vue等都是属于单例模式,我们在使用 new Vue 的时候,返回的也会是同一个实例的,简单实现

// 方式一
let Car = function () {
  const inst = this
  this.num = 0
  // todo: 其他内容
  Car = function () {
    return inst
  }
}

const miniCar = new Car()
const baoMa = new Car()

console.log(minicar === baoMa) // true

// 方式二

let Car;
  (function () {
    let intr = null
    Car = function Car() {
      if (intr) {
        return intr
      }
      intr = this
      this.name = "Car"
      // todo: 其他内容
    }
  }())

const miniCar = new Car()
const baoMa = new Car()

console.log(miniCar === baoMa) // true

// 方式三

let Car = function () {
  let inst = this
  this.name = "Car"
  // todo: 其他内容

  Car = function () { 
    return inst
  }
}

const miniCar = new Car()
const baoMa = new Car()

console.log(miniCar === baoMa) // true

// 方式四 隐式缓存

let Car = function () {
  if (Car.inst) return Car.inst
  this.name = "Car"
  // todo: 其他内容
  Car.inst = this
}

const miniCar = new Car()
const baoMa = new Car()

console.log(miniCar === baoMa) // true

正常我们在定义单例模式时应该注重一个自身的命名空间问题,很多时候,我们更多的可能是直接用一个对象来表达如这种:

const Inst = {
  data: () => {
    // todo:
  },
  methods: {
  },
  ...
}

这样就拥有了一个自己的独立命名空间

模块分明

我们在使用时,尽可能的将模块分明开来

const Project = {
  common: {
    // todo:
  },
  util: {
    // todo:
  },
  other: {
    // todo:
  },
  ...
}

// 使用

Project.util.xx

一个独立于其他的命名空间,其中的代码逻辑分离开来,独立模块,使得结构更加分明

单例对象

我们可以将一些对象定义为静态

const Car = (function () {
  let opt = {
    SPEED: 100,
    PRICE:'12W'
  }
  return {
    get(key) {
      return opt[key] || null
    },
    set(key, value) {
      opt[key] = value
    }
  }
}())

console.log(Car.get('PRICE')) // 12W

这里我们只能使用 Car 中的 opt 定义的一些属性,这里我们定义了方法 set 来写操作,若不定义 set 就是我们说的静态了,只能读取了

惰性单例

延迟创建

const LazySingle = (function () { 
  let _inst = null
  function Single() {
    return {
      methods: {
        // todo:
      },
      version:'1.0.0'
    }
  }
  return function () {
    if (!_inst) {
      _inst = new Single()
    }
    return _inst
  }
}())

let test = LazySingle().version
console.log(test) // 1.0.0

所谓单例,就是在一个文件或是一个系统中只能存在一个实例或是一个对象,尽可能的将各个模块的代码梳理得井井有条,更为规范

你可能感兴趣的:(JavaScript设计模式,javascript,设计模式,单例模式)