单例模式 ⭐
定义
单例模式(Singleton Pattern),调用一个类,任何时候返回的都是同一个实例
- 一个类只有一个实例
- 可以全局访问
实现
js
class Modal {
constructor(name) {
this.name = name
}
getName = function () {
return this.name
}
}
const CreateModal = (function () {
let instance = null
return function (name) {
if (!instance) {
instance = new Modal(name)
}
return instance
}
})()
let login = new CreateModal('登录框')
let form = new CreateModal('表单框')
console.log(login === form) // true
console.log(login.getName()) // '登录框'
console.log(form.getName()) // '登录框'
js
const singleton = function (fn) {
let result
return function () {
return result || (result = fn.apply(this, arguments))
}
}
const createLoginLayer = function () {
const div = document.createElement('div')
div.innerHTML = '我是登录浮窗'
div.style.display = 'none'
document.body.appendChild(div)
return div
}
const createSingleLoginLayer = singleton(createLoginLayer)
document.getElementById('loginBtn').onclick = function () {
const loginLayer = createSingleLoginLayer()
loginLayer.style.display = 'block'
}
应用场景
- 弹窗
- 购物车
- Vuex 的 store
- EventBus