概述
单例模式(Singleton Pattern)是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点来访问该实例。单例模式通常用于管理全局状态、共享资源或配置对象等场
特点
- 唯一实例:确保一个类只有一个实例。
- 全局访问:提供一个全局访问点,方便其他代码访问该实例。
- 延迟初始化:实例在第一次被请求时才创建,而不是在程序启动时立即创建。
那么单例模式的使用场景都有什么呢?
- 在 Vue 应用中,Vuex 的 Store 就是单例模式的应用
- 全局的公共提示框、通知栏等
- ......
那么单例模式如何实现?
这就是一个简单的单实例实现、下面是实现步骤
1. 使用私有属性来存储modal的状态
2. 使用私有属性来存储实例
3. 使用私有属性来控制constructor 防止外部实例化
4. 外部只能使用getInstance来获取实例
js
class PublicModal {
private state: string = "hide";
private static instance: PublicModal | null;
private constructor() {}
static getInstance(): PublicModal {
if (this.instance === null) {
this.instance = new PublicModal();
}
return this.instance;
}
show() {
if (this.state === "show") return;
this.state = "show";
}
hide() {
if (this.state === "hide") return;
this.state = "hide";
}
}
const modal1 = PublicModal.getInstance();
const modal2 = PublicModal.getInstance();
那怎么不用class来实现单例模式呢?
我想很多人第一想法应该是用闭包的思想去维护单一实例状态 那么接下来我将使用闭包来实现单例模式
js
const Singleton = (function () {
let instance;
function createInstance() {
return {
data: {
show: true,
},
hideMethod() {
if (!this.show) return;
this.show = false;
},
showMethod() {
if (this.show) return;
this.show = true;
},
}
return {
getInstance() {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
单例模式的优缺点
优点
减少内存开销 由于只有一个实例存在,单例模式可以减少内存占用,特别是在需要频繁创建和销毁对象的场景中
控制实例化过程 单例模式通过私有构造函数和静态方法控制实例化过程,防止外部代码随意创建实例。增强了代码的安全性和可控性。
全局访问点 通过单例模式,可以提供一个全局访问点,方便其他模块或组件访问该实例。 避免了频繁传递实例的麻烦,简化了代码结构
全局唯一实例单例模式确保一个类只有一个实例,避免了重复创建对象,节省了系统资源。适用于需要全局唯一对象的场景,例如公共交互组件、日志记录等
缺点
扩展性差 单例模式的设计初衷是确保一个类只有一个实例,因此难以扩展为多个实例如果需要支持多个实例,单例模式可能不再适用
违反单一职责原则单例类通常既负责业务逻辑,又负责实例管理,这违反了单一职责原则,如果单例类的职责过多,可能导致代码臃肿和难以维护