单例模式是一种常用的模式,有一些对象我们往往只需要一个,比如线程池、全局缓存、浏览器中的 window 对象等。单例模式用于保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式包含如下角色:
class Singleton {
private static singleton: Singleton;
private constructor() {}
public static getInstance(): Singleton {
if (!Singleton.singleton) {
Singleton.singleton = new Singleton();
}
return Singleton.singleton;
}
}
function show(): void {
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
if (singleton1 === singleton2) {
console.log("two singletons are equivalent");
} else {
console.log("two singletons are not equivalent");
}
}
单例模式的作用是保证一个类仅有一个实例,并提供一个访问它的全局访问点。由于单例模式在内存中只有一个实例,减少了内存开支,特别是一个对象需要频繁地创建、销毁时,而且创建或销毁时性能又无法优化,单例模式的优势就非常明显。