ES6 實現單例模式


單例模式:保證一個類只有一個實例,並且提供它的全局訪問點。

  • 通過構造函數
class Singleton {
  constructor() {
    if(!Singleton.instance) {
      // 將 this 掛載到單例上
      Singleton.instance = this
    }
    return Singleton.instance
  } 
}
const a = new Singleton() 
const b = new Singleton()
console.log(a === b)
  • 通過靜態方法
class Singleton {
  static instance = null

  static getInstance() {
    if(!Singleton.instance) {
      Singleton.instance = new Singleton()
    }
    return Singleton.instance
  }
}
const a = new Singleton() const b = new Singleton() console.log(a === b)
  • 通過代理模式
class Cat {}

const createSingleCat = (() => {
  let instance
  return () => {
    if (!instance) {
      instance = new Cat()
    }
    return instance
  }
})()
const a = new Singleton()
const b = new Singleton()
console.log(a === b)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM