2021.11.26
關於JS 實作Singleton模式有許多教學文章,但大多都以function方式定義,而非Class方式定義,找了許多終於發現有一個影片是以Class 方式定義,是以Object.freeze 方式實踐,以下是參考影片寫出:
class Singleton{
constructor(){
if(Singleton.instance instanceof Singleton){
return Singleton.instance}
this.SingletonObject={
name:'Singleton',
version:1
}
Object.freeze(this)
Singleton.instance = this
}
get(key){
return this.SingletonObject[key]
}
}
let a = new Singleton()
let b = new Singleton()
console.log(a===b)//output true