单例模式,是一种常用的软件设计模式;
单例模式就是确保一个类在任何情况下都只有一个实例,并提供一个全局访问点
类图
实现代码
class Singleton {
private static instance: Singleton;
// 私有构造函数防止外部实例化
private constructor() {
console.log('Singleton instance created');
}
// 全局访问点
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
// 业务方法
public someBusinessLogic(): void {
console.log('Executing business logic...');
}
}
// 使用示例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true,两者是同一个实例
instance1.someBusinessLogic();
经典场景
jQuery
// 无论引入多少次 jQuery,都只会返回第一个 实例
if (window.jQuery != null) {
return window.jQuery;
} else {
//init~~~~~~~
}
模态窗口
class Login {
constructor() {
this.element = document.createElement('div');
this.element.innerHTML = (
`
用户名 <input type="text"/>
<button>登录</button>
`
);
this.element.style.cssText = 'width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; display: block;';
document.body.appendChild(this.element);
}
show() {
this.element.style.display = 'block';
}
hide() {
this.element.style.display = 'none';
}
}
Login.getInstance = (function () {
let instance;
return function () {
if (!instance) {
instance = new Login();
}
return instance;
}
})();
document.getElementById('showBtn').addEventListener('click', function (event) {
Login.getInstance().show();
});
document.getElementById('hideBtn').addEventListener('click', function (event) {
Login.getInstance().hide();
});
打赏作者
您的打赏是我前进的动力
微信
支付宝
工厂模式
上一篇
评论