JS的单例模式非常简单。
一、概念
只要在实例化的时候,保证只是实例化一次,将实例化的实力用闭包存起来,供以后调用的时候判断是否已经存在实力化。说得专业一些就是一个构造函数在构造一个对象以后,我们在构造函数中用一个参数存下该对象,当构造函数调用的时候,判断这个参数是否已经有值。
二、应用
这个应用相对来说是比较广泛的,比如说一个弹框弹出的时候不想出现多个弹框(vue等mvvm框架的弹框一般是组件,不需要考虑)、比如只想要页面刷新的时候调用共用接口,一旦接口成功调用过就不再调用、视频或者音频打开的时候再打开另一个…
三、作用
- 保证某个类的对象的唯一性
- 模块间通信
- 防止变量污染
书里告诉我们:
-
创建完之后,只有一个实例,之后再怎么创建,都是这一个,方便实例管理,提供了对实例的受控访问。
-
对于频繁创建,销毁对象,这个单例模式实现了对象统一,内存只占有一个对象内存分量,在频繁创建中,大大的节约了系统内存。
四、代码
下边直接上代码:
es6以后的实现方式:
class Singleton {
constructor(name) {
this.name = name // 当前的单例模式的名称
this.instance = null
}
static getInstance(name) {
if(!this.instance) {
this.instance = new Singleton (name);
}
return this.instance;
}
}
我们来验证一来单例模式的应用。
用弹框来验证吧。
在页面上设置一个点击弹框的按钮
<button id="popShowBtn">弹框</button>
点击id是popShowBtn的按钮,弹框弹框,如下:
class popShowSingleton {
constructor(name) {
this.name = name // 当前的单例模式的名称
this.instance = null
this.init()
}
init() {// 创建一个div,弹框用
var div = document.createElement('div')
div.classList.add('pop-show-layer')
div.innerHTML = this.name
document.body.appendChild(div)
console.log(this.name)
}
static getInstance(name) {
if(!this.instance) {
this.instance = new popShowSingleton (name);
}
return this.instance;
}
}
const btn = document.getElementById('popShowBtn')
btn.addEventListener('click', function(){
popShowSingleton.getInstance('我是弹框内容')
}, false)
至此,单例模式已经完成。