js——发布-订阅模式(观察者模式)
对象间的一种一对多的关系,当一个对象发生改变时,所有依赖它的对象都会得到通知。
比如wb上的明星和其粉丝的关系,粉丝在wb上订阅了明星,所以当明星在wb上发表动态时所有粉丝都将得到通知。
js具体实现:事件监听器
有三个角色:
- 发布者(publisher)
- 发布功能(publish(发布内容))
- 订阅者(subscriber)
- 订阅功能(distribute(订阅内容))
- 消息分发器(msgDistributor)
- 缓存 subscribers
- 发布功能(publish(发布内容))
- 订阅功能(distribute())
wb例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function fensi(name, weibo) {
this.name = name;
this.weibo = weibo;
const guanzhu = (mingxingName) => {
this.weibo.subscribe(mingxingName, this.name)
}
return {guanzhu}
}
function mingxing(mingxingName, weibo) {
this.mingxingName = mingxingName;
this.weibo = weibo;
const fabu = (callback) => {
this.weibo.publish(mingxingName, callback)
}
return{fabu}
}
function weibo() {
let mf = {};
//{'明星名': '粉丝1', '粉丝2', ...}
const publish = (pubType, callback) => {
Array.isArray(mf[pubType]) &&
mf[pubType].forEach(item => {
callback(item);
})
}
const subscribe = (subType, subName) => {
!Array.isArray(mf[subType]) && (mf[subType] = [])
mf[subType].push(subName);
}
return {
publish,
subscribe
}
}
// 小明和小芳关注了wyf,小华和小美关注了lh,小芳和小美关注了yyqx,只有wjw没有人关注。
const weibo1 = new weibo();
const xiaoming = new fensi('小明', weibo1);
const xiaofang = new fensi('小芳', weibo1);
const xiaohua = new fensi('小华', weibo1);
const xiaomei = new fensi('小美', weibo1);
const xiaomeng = new fensi('小萌',weibo1);
const wuyifan = new mingxing('wyf', weibo1);
const luhan = new mingxing('lh', weibo1);
const yiyangqianxi = new mingxing('yyqx', weibo1);
const wangjingwei = new mingxing('wjw', weibo1);
xiaoming.guanzhu('wyf');
xiaofang.guanzhu('wyf');
xiaohua.guanzhu('lh');
xiaomei.guanzhu('lh');
xiaofang.guanzhu('yyqx');
xiaomei.guanzhu('yyqx');
xiaomeng.guanzhu('wjw');
wuyifan.fabu((fensi) =>console.log(fensi + '你好!很高兴你关注了我!我是wyf'));
luhan.fabu((fensi) =>console.log(fensi + '你好!很高兴你关注了我!我是lh'));
yiyangqianxi.fabu((fensi) =>console.log(fensi + '你好!很高兴你关注了我!我是yyqx'));
wangjingwei.fabu((fensi) =>console.log(fensi + '你好!很高兴你关注了我!我是wjw'));
</script>
</body>
</html>