單例模式
單例模式指的是一個類只能有一個實例存在。
在實際應用中有些場景我們只需要唯一實例的存在,如果出現多個實例就會出現問題,這個時候我們就需要用到單例模式。比如線程池,緩存,硬件設備等。
實現思路
每個類中都有一個構造函數 constructor
,當我們 new
這個類時,實際上就是在調用這個構造函數。比如我們定義了一個 Car
類,實例化了一隻叫“茶”的小貓咪和一隻叫“菊”的小貓咪。此時我們聲明瞭兩個 Car
的實例。
class Car {
name: string
constructor(name) {
this.name = name
}
}
const cha = new Car('茶')
const ju = new Car('菊')
如果我們把構造函數變成私有函數,外部就無法將這個類實例化。
所以,只要我們把一個類的構造函數私有化,並在類內部實例化出唯一的一個實例,就可以實現單例模式了。
class Singleton {
private constructor() {
// 初始化
}
// 聲明一個私有的靜態屬性作爲唯一的實例
private static INSTANCE: Singleton = new Singleton()
// 暴露一個公開的方法用於獲取實例
public getInstance() {
return Singleton.INSTANCE
}
}
餓漢模式和懶漢模式
單例模式又分爲餓漢模式和懶漢模式
- 餓漢模式:指全局的單例實例在類裝載時構建
- 懶漢模式:指全局的單例實例在第一次被使用時構建
餓漢模式
class Singleton {
private constructor() {
// 初始化
}
// 聲明一個私有的靜態屬性作爲唯一的實例
private static INSTANCE: Singleton = new Singleton()
// 暴露一個公開的方法用於獲取實例
public getInstance() {
return Singleton.INSTANCE
}
}
餓漢模式
class Singleton {
private constructor() {
// 初始化
}
// 聲明一個私有的靜態屬性作爲唯一的實例
private static INSTANCE?: Singleton = null
// 暴露一個公開的方法用於獲取實例
public getInstance() {
if (!Singleton.INSTANCE) {
Singleton.INSTANCE = new Singleton()
}
return Singleton.INSTANCE
}
}