订阅,订餐,就是等到一个时机就触发
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
window.onload = function(){
//主题,保存状态,状态变化后触发所有者观察者对象
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state
this.notifyAllObservers()
}
notifyAllObservers() {
this.observers.forEach(observer =>{
observer.update()
})
}
attach(observer) {
this.observers.push(observer)
}
}
class Observer{
constructor(name,subject) {
this.name = name;
this.subject = subject;
this.subject.attach(this)
}
update() {
console.log(`${this.name} update,state: ${this.subject.getState()}`)
}
}
let s = new Subject()
let o1 = new Observer('01',s)
console.log(o1)
s.setState(1)
}
</script>
</html>