当前位置:网站首页>简化理解:发布订阅
简化理解:发布订阅
2022-07-24 15:32:00 【InfoQ】
// 发布者 Publisher
class Pub {
constructor() {
this.deps = [];
}
addDep(dep) {
this.deps.push(dep);
}
publish(dep) {
this.deps.forEach(item => item === dep && item.notify());
}
}
// 订阅者 Subscriber
class Sub {
constructor(val) {
this.val = val;
}
update(callback) {
callback(this.val)
}
}
// 调度中心
class Dep {
constructor(callback) { // 核心是这个 callback 函数;
this.subs = [];
this.callback = callback;
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(item => item.update(this.callback));
}
}
let pub = new Pub() // 实例化一个发布者
// 实例化一个调度中心,传入一个用于处理数据的函数;
const dep1 = new Dep((data) =>
console.log('我是调度中心,我先把消息处理一下,然后发给 ===》》》', data))
let sub1 = new Sub("订阅者1") // 实例化订阅者1
let sub2 = new Sub("订阅者2") // 实例化订阅者2
pub.addDep(dep) // 发布者绑定调度中心
dep.addSub(sub1) // 调度中心添加订阅者1
dep.addSub(sub2) // 调度中心添加订阅者2
pub.publish(dep) // 发布者把消息推给调度者
// 我是调度中心,我先把消息处理下先 订阅者1
// 我是调度中心,我先把消息处理下先 订阅者2
- 发布者需要有两个方法,绑定调度者 Dep,把消息推知给调度者;
- 调度者也有两个方法,绑定订阅者 Sub,把消息推送给订阅者;
- 订阅者有一个方法,执行函数;
function weatherWarning(weatherStatus){
if(weatherStatus==='warning'){ // 糟糕的天气
buildingsite.stopwork() // 工地停工
ships.mooring() // 船舶停航
tourists.canceltrip() // 旅游取消
}
}
weatherWarning("warning") // 发布坏天气通知


const EventEmit = function() { // 调度中心
this.events = {};
this.on = function(name, cb) { // 绑定订阅器
if (this.events[name]) {
this.events[name].push(cb); // 支持同一个订阅器执行多个事情
} else {
this.events[name] = [cb];
}
};
this.trigger = function(name, ...arg) { // 发送消息
if (this.events[name]) {
this.events[name].forEach(eventListener => {
eventListener(...arg);
});
}
};
};
let weatherEvent = new EventEmit() // 实例化一个调度中心
weatherEvent.on('warning', function () { // 绑定发布通知的关系
// buildingsite.stopwork()
console.log('buildingsite.stopwork()')
})
weatherEvent.on('warning', function () { // 绑定发布通知的关系
// ships.mooring()
console.log('ships.mooring()')
})
weatherEvent.on('warning', function () { // 绑定发布通知的关系
// tourists.canceltrip()
console.log('tourists.canceltrip()')
})
weatherEvent.trigger('warning') // 发布消息
class Subject{// 被观察者
constructor(){
this.observers=[]
}
add(observer){
this.observers.push(observer)
}
notify(weatherStatus){
this.observers.forEach(i=>i(weatherStatus))
}
}
let sub = new Subject()
sub.add((reason)=>{
// buildingsite.stopwork()
console.log('工地停工,因为天气:',reason)
})
sub.add((reason)=>{
// ships.stopwork()
console.log('船舶停航,因为天气:',reason)
})
sub.add((reason)=>{
// tourists.canceltrip()
console.log('旅游取消,因为天气:',reason)
})
sub.notify("warning") // sub 发布消息
// 工地停工,因为天气: warning
// 船舶停航,因为天气: warning
// 旅游取消,因为天气: warning
element.addEventListener('click', function(){
//...
})
边栏推荐
- Multus of kubernetes multi network card scheme_ CNI deployment and basic use
- C. Recover an RBS
- 华为无线设备配置WPA2-802.1X-AES安全策略
- 力扣 31.下一个排列--双指针法
- Is it safe for Huatai Securities to open an account? I don't know how to operate it
- YOLO5Face:为什么要重新发明人脸检测器
- MySql函数
- DS binary tree - parent and child nodes of binary tree
- C # exit login if there is no operation
- Choice of advanced anti DDoS IP and CDN in case of DDoS
猜你喜欢

接参处理和@Param

JSON file editor

Do you understand the working principle of gyroscope?

Fastjson code execution cve-2022-25845

27.目录与文件系统

【Bug解决】Win10安装pycocotools报错

Istio1.12: installation and quick start

JUC源码学习笔记3——AQS等待队列和CyclicBarrier,BlockingQueue

Outlook tutorial, how to create tasks and to DOS in outlook?

Getting started with mongodb
随机推荐
[tkinter美化] 脱离系统样式的窗口(三系统通用)
DS diagram - the shortest path of the diagram (excluding the code framework)
Citic securities account opening process, is it safe to open an account on your mobile phone
JMeter - call the interface for uploading files or pictures
C# 无操作则退出登陆
[bug solution] error in installing pycocotools in win10
Database learning – select (multi table joint query) [easy to understand]
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)---第一题 不要浪费金币 (已完结)
Circular structure practice
Huawei camera capability
What is a firewall? What role can firewalls play?
Fastjson code execution cve-2022-25845
Calculate the M-day moving average price of two stocks
DS binary tree - parent and child nodes of binary tree
ZABBIX administrator forgot login password
C# - partial 关键字
Leetcode-09 (next rank + happy number + full rank)
Is it safe for Huatai Securities to open a mobile account and will it be leaked
How to deal with being attacked? Advanced anti DDoS IP protection strategy
Android section 13 detailed explanation of 03sqlite database