观察者模式(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)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。