观察者模式
文章目录
观察者模式(Observer)
定义:属于行为型模式的一种,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。
实现
<span id="num">1</span>
<button onclick="numAdd()">+</button> var num = document.getElementById('num')
function numAdd() {
notice.setState(Math.floor(Math.random() * 10))
num.innerText = notice.state + Math.floor(Math.random() * 10)
}
function Theme() {
this.observers = []
this.state = 0
this.setState = function (newVal) {
this.state = newVal
this.notifyAllObservers()
}
this.attach = function (observer) {
this.observers.push(observer)
}
this.notifyAllObservers = function () {
this.observers.forEach((item) => item.updated(this.state))
}
}
function Observer(name) {
this.name = name
this.updated = function (e) {
console.log(`${this.name}接收到了新消息`, e)
}
}
var notice = new Theme()
var observer1 = new Observer('观察者1')
var observer2 = new Observer('观察者2')
notice.attach(observer1)
notice.attach(observer2)
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论