单例模式是指在一个类中只能有一个实例,即使多次实例化该类,只返回第一次实例化后的实例对象。单例模式可以减少不必要的内存开销,并且在减少全局的函数和变量冲突也具有中也有意义。
惰性单例模式,只有当触发创建实例对象时,实例对象才会被创建。
class Singleton {
constructor(attr) {
this.attr = attr
}
static getInstance(attr) {
if (!this.instance) {
this.instance = new Singleton(attr)
}
return this.instance
}
}
let a = new Singleton('a')
let b = new Singleton('b')
console.log(a === b)
实现一个alert组件
class 方式创建单例模式,定义一个用于获取实例的getInstance 方法
class Alert {
constructor(content) {
this.content = content
this.init()
}
init() {
this.alert = document.createElement('div')
this.alert.innerHTML = this.content
this.alert.style.display = 'none'
document.body.appendChild(this.alert)
}
show() {
this.alert.style.display = 'block'
}
hide() {
this.alert.style.display = 'none'
}
static getInStance(content) {
if(!this.instance) {
this.instance = new Alert(content)
}
return this.instance
}
}
let a = Alert.getInStance('a')
let b = Alert.getInStance('b')
console.log(a === b)
使用闭包实现
function Init(content) {
this.alert = document.createElement('div')
this.alert.innerHTML = content
this.alert.style.display = 'none'
document.body.appendChild(this.alert)
}
Init.prototype.show = function() {
console.log('show')
this.alert.style.display = 'block'
}
Init.prototype.hide = function() {
console.log('none')
this.alert.style.display = 'none'
}
var alertSingle = (function() {
var instance = null
return function(content) {
if(!instance) {
instance = new Init(content)
}
return instance
}
})()
let a = new alertSingle('a')
let b = new alertSingle('b')
console.log(a === b)
网友评论