设计模式
- 为了解决 某一类问题的一个优化过的代码解决方案
- 单例模式:
- 一个构造函数,一生只能创建一个实例化对象
- 准备一个变量默认值为null,然后在第一次实例化的时候 给这变量赋值为实例化对象
- 后续在调用实例化的时候,就不再创建实例化对象了,而是拿到提前准备好的变量
class Dialog {
constructor() {
console.log('在页面中 创建了一个 弹出层')
}
}
let instance = null
function newDialog() {
if(instance === null) {
instance = new Dialog()
}
return instance
}
let d1 = newDialog()
newDialog()
newDialog()
单例模式升级1
class Dialog {
constructor() {
console.log('在页面中 创建了一个 弹出层')
}
}
const newDialog = (function() {
let instance = null
return function() {
if(instance === null) {
instance = new Dialog()
}
return instance
}
})()
let d1 = newDialog()
let d2 = newDialog()
单例模式升级2
const Dialog = (function() {
let instance = null
class Dialog {
constructor(title) {
this.title = title
console.log('在页面中 创建了一个 弹出层')
}
setTitle(newTitle) {
this.title = newTitle
}
}
return function(type) {
if(instance === null) {
instance = new Dialog()
}
instance.setTitle(type)
return instance
}
})()
let d1 = Dialog('警告')
console.log(d1)
let d2 = Dialog('通用')
console.log(d2)