單例模式:保證一個類只有一個實例,並且提供它的全局訪問點。
- 通過構造函數
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)