今天学习vue 源码看到了观察模式以下是我的个人总结
场景
有三个人来找工作 但是目前公司没有岗位 所以留下了三个人的联系方式 等有工作再通知他们三个人 所以观察者模式是一个一对多的关系 所以需要两个主体 一个公司,另一个需要找工作的人
创建公司class
class Company {
constructor() {
this.needJobPerson = [] //收集前来找过工作的人
}
//留下找工作人的联系方式
addObserver(person) {
this.needJobPerson.push(person)
}
//通知找工作的人有新的工作发布了
notify(task) {
this.needJobPerson.forEach((observer) => observer.update(task))
}
}
创新找工作的人class
class Observer {
constructor(name) {
this.name = name
}
update({ taskType, taskInfo }) {
// 假设工作分为白班夜班
// 如果是白班,则接受
if (taskType !== 'day') {
console.log(`${this.name}不想找别的除了白天时间段的工作`)
return
}
this.acceptJob(taskInfo)
}
acceptJob(info) {
console.log(`${this.name}接受了${info}工作`)
}
}
初始化流程
//创建一个公司
const company = new Company()
//创建来找工作的3个人
const person1 = new Observer('张三')
const person2 = new Observer('李四')
const person3 = new Observer('王五')
//公司目前没有合适的职位,所以先把员工的联系方式留下
company.addObserver(person1)
company.addObserver(person2)
company.addObserver(person3)
公司有了新的岗位通知需要找工作的人
工作时间<input type="text" id="time" />
工作类型<input type="text"id="type" />
<button id="btn">公司通知有新工作了</button>
当我点击通知按钮 我就去给找工作的人群发送消息
//公司发布了一个新的工作
document.getElementById('btn').addEventListener('click', () => {
//发布一个工作
company.notify({
taskType: document.getElementById('time').value,
taskInfo: document.getElementById('type').value,
})
})
在notify方法中我去遍历needJobPerson执行update这样就可以收到消息了
观察者模式与回调函数很像 区别在于观察者模式是一对多 而回调函数是一对一
看到这里,不知道你可以理解观察者模式了?