当前位置: 首页 > Web前端 > JavaScript

观察者模式

时间:2023-03-27 11:41:37 JavaScript

观察者模式(Observer)定义:是一种行为模式,定义了一对多的依赖关系,允许多个观察者对象同时监视某个主体对象。主题对象将状态更改通知所有观察者对象,使它们能够自动更新自己。现实1+varnum=document.getElementById('num')functionnumAdd(){notice.setState(Math.floor(Math.random()*10))num.innerText=notice.state+Math.floor(Math.random()*10)}functionTheme(){this.observers=[]this.state=0这个.setState=function(newVal){this.state=newValthis.notifyAllObservers()}this.attach=function(observer){this.observers.push(observer)}this.notifyAllObservers=function(){this.observers.forEach((item)=>item.updated(this.state))}}functionObserver(name){this.name=namethis.updated=function(e){console.log(`${this.name}接收了新消息`,e)}}varnotice=newTheme()varobserver1=newObserver('观察者1')varobserver2=newObserver('观察者2')notice.attach(observer1)notice.at转速表(观察者2)