一、基本思想:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js实现观察者模式</title>
<script>
class Subject {
constructor() {
this.observers = [];
}
attach(observer) {
this.observers.push(observer)
}
notify(reason) {
this.observers.map(e => e.update(reason))
}
}
class Sub extends Subject {
constructor(name) {
super();
this.name = name;
}
getName () {
this.name = name;
}
setName (name){
this.name = name;
this.notify('修改名字')
}
}
class Observer {
constructor(name,sub){
this.name = name;
this.sub = sub;
this.sub.attach(this);
}
update(reason){
console.log(`${this.name}已经监听变化,变化原因是${reason},变化后的值是:${this.sub.name}`)
}
}
const name = 'Andy';
const sub = new Sub(name);
const observer1 = new Observer('观察者1',sub);
const observer2 = new Observer('观察者2',sub);
sub.setName(window.prompt('请输入sub的名字',name));
</script>
</head>
<body>
</body>
</html>
``
## 二、应用
```javascript
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js实现观察者模式</title>
<script>
/**
* 小A在公司C完成了笔试及面试,小B也在公司C完成了笔试。他们焦急地等待结果,每隔半天就电话询问公司C,导致公司C很不耐烦。
*
* 一种解决办法是 AB直接把邮箱联系方式留给C,有结果的话C自然会通知AB
*/
//被观察者,即客体
class Subject {
constructor() {
this.observers = [];//观察者列表
}
attach(observer) {
this.observers.push(observer)
}
notify(reason) {
this.observers.map(e => e.accept(reason))
}
}
class Company extends Subject {
constructor(name) {
super();
this.name = name;
}
getName () {
this.name = name;
}
setName (name){
this.name = name;
}
hasResult(){
this.notify('录取结果已经公布,请您提示查收!')
}
}
//观察者
class Observer {
constructor(name,number,com){
this.name = name;
this.number = number;
this.com = com;
this.com.attach(this);
}
accept(reason){
console.log(`亲爱的${this.name},${reason}详情已发送至您的邮箱${this.number}`,)
}
}
const name = '公司C';
const company = new Company(name);
const observer1 = new Observer('小A',110,company);
const observer2 = new Observer('小B',120,company);
console.log('company',company)
setTimeout(()=>{
company.hasResult()
},3000)
</script>
</head>
<body>
</body>
</html>