一、什么是设计模式?
二、单例模式
- 一个构造函数,一生只能创建一个实例化对象,(准备一个变量默认赋值为null,然后在第一次实例化的时候给这个变量赋值为实例化对象,后续在调用实例化的时候,就不再创建实例化对象了,而是拿到提前准备好的变量)
class Dialog{
constructor () {
console.log('在页面中创建一个弹出层')
}
}
let instance = null
function newDialog () {
if (instance === null){
instance = new Dialog
}
return instance
}
let d1 = newDialog()
let d2 = newDialog()
class Dialog{
constructor () {
console.log('在页面中创建一个弹出层')
}
}
const newDialog = (function () {
let instance = null
return function () {
if (instance === null){
instance = new Dialog
}
return instance
}
}) ()
const d1 = newDialog()
const d2 = newDialog()
const Dialog = (function () {
let instance = null
class Dialog {
constructor () {
this.title = ''
console.log('在页面中创建一个弹出层')
}
setTitle(newTitle) {
this.title = newTitle
}
}
return function (type) {
if (instance === null) {
instance = new Dialog()
}
instance.setTitle(type)
return instance
}
})()
const d1 = new Dialog('警告')
console.log(d1)
const d2 = new Dialog('通用')
console.log(d2)
二、策略模式
- 为了解决过多的 if...else的嵌套问题
- 核心(超时折扣案例):
- 创建一个数据结构,结果内存储着各种折扣记录,对应的值,是这个折扣的计算方式
const calcPrice = (function () {
const calcList = {
'80%' : (total) => { return (total * 0.8).toFixed(2)},
'70%' : (total) => { return (total * 0.7).toFixed(2)},
}
function inner(type, total) {
return calcList[type](total)
}
return inner
})()
console.log(calcPrice('80%',200))
const calcPrice = (function () {
const calcList = {
'70%' : (total) => { return (total * 0.7).toFixed(2)},
'80%' : total => (total * 0.8).toFixed(2),
'50%' : total => (total * 0.5).toFixed(2)
}
function inner(type, total) {
return calcList[type](total)
}
inner.add = function (type, fn){
calcList[type] = fn
}
inner.sub = function (type) {
delete calcList[type]
}
inner.getList = function () {
return calcList
}
return inner
})()
console.log(calcPrice('80%',200))
calcPrice.add('60%',total => (total * 0.6).toFixed(2))
calcPrice.sub('60%')
console.log(calcPrice.getList())
三、发布订阅模式
class observer {
constructor(name) {
this.name = name
this.msgList = {}
}
add(type,fn) {
if (this.msgList[type] === undefined) {
this.msgList[type] = []
}
this.msgList[type].push(fn)
}
tri(type) {
this.msgList[type].forEach(item => item())
}
delName(type,fn) {
this.msgList[type] = this.msgList[type].filter(item => item !== fn)
}
}
const o1 = new observer('小刚')
console.log(o1)
const bookName1 = 'js从入门到入土'
const bookName2 = '颈椎病的预防'
const fnA = () => console.log('张三,想购买这本书')
const fnB = () => console.log('李四,想购买这本书')
const fnC = () => console.log('王五,想购买这本书')
o1.add(bookName1,fnA)
o1.add(bookName1,fnB)
o1.add(bookName1,fnC)
o1.delName(bookName1,fnB)
o1.tri(bookName1)
console.log('有预约者之后的对象',o1);