返回
JavaScript设计模式与开发实践:模式篇(1)——单例模式
前端
2023-11-19 07:59:14
前言
在JavaScript的世界中,设计模式如同指南针,指引着我们走向更优雅、更可靠、更易维护的代码。单例模式就是其中一颗璀璨的明珠,它在JavaScript中发挥着至关重要的作用。
单例模式:确保只有一个实例
单例模式的精髓在于:确保一个类只有一个实例,并提供一个访问它的全局访问点。
1. 代理模式:巧妙实现单例
代理模式是实现单例模式的经典手法。我们创建一个代理类,该类负责实例化真正的单例类并返回其实例。这样,我们就可以在需要时访问单例类,而无需关心它的实例化过程。
class Singleton {
static getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
2. 惰性单例:按需创建实例
惰性单例模式是一种变种,它只有在第一次需要实例时才创建实例。这可以节省内存空间,并提高性能。
let instance;
function getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
const instance1 = getInstance();
const instance2 = getInstance();
console.log(instance1 === instance2); // true
应用场景:创建唯一节点和浮窗
单例模式在JavaScript中有着广泛的应用,其中包括创建唯一节点和浮窗。
1. 创建唯一节点:避免重复创建
const div = document.getElementById('my-div');
if (!div) {
const newDiv = document.createElement('div');
newDiv.id = 'my-div';
document.body.appendChild(newDiv);
}
2. 创建唯一浮窗:始终只有一个浮窗
class FloatingWindow {
static getInstance() {
if (!this.instance) {
this.instance = new FloatingWindow();
}
return this.instance;
}
show() {
// 显示浮窗
}
hide() {
// 隐藏浮窗
}
}
const floatingWindow1 = FloatingWindow.getInstance();
const floatingWindow2 = FloatingWindow.getInstance();
floatingWindow1.show();
floatingWindow2.hide();
console.log(floatingWindow1 === floatingWindow2); // true
结语
单例模式是JavaScript设计模式中的一颗璀璨明珠,它确保只有一个实例,并提供一个访问它的全局访问点。代理模式和惰性模式是实现单例模式的两种经典手法,它们在JavaScript中发挥着至关重要的作用。
掌握单例模式,可以帮助我们在JavaScript中创建唯一节点、浮窗等,提升代码的健壮性和可维护性。