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