哎,写这玩意就得白话一段,初学js时,只知道写出来的代码能实现出来自己想要的东西,自己就不会过多的去关注其他,但随着做开发时间长了,自己也想去开发点东西,或者去理解一些其他人的代码时,总会有着不清楚,看不懂的尴尬。
初听单例模式时,还是在一次面试,面试官问什么是单例模式,大脑直接宕机了,单例模式,听说过工厂模式,没听说过单例模式啊,尴尬啊,现在其实也不清楚。
趁着这个机会,就一起学习一下,整理一下单例模式,让它彻底转化为我之利刃,为我们所用。
文章目录
什么是单例模式?
单例模式是一种设计模式,它确保一个类只有一个实例,并提供一个全局访问点来获取这个唯一的实例。
您可以把它想象成:
- 国家的总统:一个国家在任期内只有一位总统。
- 电脑的回收站:无论你从哪个磁盘分区删除文件,打开的都是同一个回收站。
- 任务管理器:一个系统中的任务管理器实例只能有一个,这样才能方便系统去统筹所有的任务。
为什么要用?
在一些场景的前提下,我们需要某个对象,在全局的范围中,有且仅有一个对象实例的存在,这样方便我们全局的访问以及管理。
如果创建了多个实例,会导致一些我们所不期望的问题:
- 资源浪费
- 数据不一致
- 程序执行不统一
特点
优点:
- 保证一个类只有一个实例
- 提供全局访问点
- 避免重复创建对象,节省内存
缺点:
- 违反单一职责原则
- 可能产生隐藏的依赖关系
- 不利于单元测试(难以模拟)
关键实现要点
要实现一个单例,通常需要做到以下两点:
- 私有化构造函数:防止外部使用
new关键字随意创建多个实例。 - 提供一个静态方法(如
getInstance),该方法负责检查实例是否已经存在:- 如果已存在,则返回这个已有的实例。
- 如果不存在,则创建一个新的实例并返回,同时将其保存下来以备下次使用。
实现方式
1.对象字面量
const Singleton = {
instanceId:Math.random(),//使用instanceid作为单例的唯一标志
config: {
apiUrl: 'https://api.example.com',
timeout: 5000
},
getData() {
console.log('Getting data from:', this.config.apiUrl);
},
updateConfig(newConfig) {
this.config = {
...this.config, ...newConfig };
}
}
// 使用
Singleton.getData();
Singleton.updateConfig({
timeout: 3000 });
2.闭包实现
const Singleton = (function() {
let instance;
function createInstance() {
const object = {
counter: 0,
increment() {
this.counter++;
console.log('Counter:', this.counter);
},
getCounter() {
return this.counter;
}
};
return object;
}
return {
getInstance() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 使用
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
instance1.increment(); // Counter: 1
instance2.increment(); // Counter: 2
console.log(instance1 === instance2); // true
3.Class实现
class Singleton {
static instance;
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this.data = [];
this.createdAt = new Date();
Singleton.instance = this;
}

最低0.47元/天 解锁文章
1416

被折叠的 条评论
为什么被折叠?



