当前位置:网站首页>简化理解:发布订阅
简化理解:发布订阅
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(){
//...
})
边栏推荐
- Jmeter-调用上传文件或图片接口
- [300 opencv routines] 238. Harris corner detection in opencv
- MATLAB image defogging technology GUI interface - global balance histogram
- Istio1.12:安装和快速入门
- Which securities company is the best and safest to open an account? How to open an account and speculate in stocks
- 4279. Cartesian tree
- [bug solution] error in installing pycocotools in win10
- 云开发单机版图片九宫格流量主源码
- C# SQLite Database Locked exception
- Android SQLite database practice
猜你喜欢

25. From disk to file

Simple encapsulation of wechat applet wx.request

Kubectl_ Easy to use command line tool: Oh my Zsh_ Tips and tricks

27. Directory and file system

27.目录与文件系统

Activity Registration: how to quickly start the open source tapdata live data platform on a zero basis?
![[quantitative test]](/img/df/f2d8b252169213af340f3e535bddef.png)
[quantitative test]

【AdaptiveAvgPool3d】pytorch教程

2022 RoboCom 世界机器人开发者大赛-本科组(省赛)-- 第五题 树与二分图 (已完结)

C# - partial 关键字
随机推荐
Jmeter-调用上传文件或图片接口
Join parameter processing and @param
Existence form and legitimacy of real data in C language (floating point number)
Research on stability of time-delay systems based on Lambert function
【TA-霜狼_may-《百人计划》】图形3.4 延迟渲染管线介绍
Do you understand the working principle of gyroscope?
循环结构practice
Intuitive understanding of various normalization
Introduction to single chip microcomputer: LED bidirectional water lamp
【量化测试】
Experience summary of slow SQL problems
Simple encapsulation of wechat applet wx.request
ZABBIX administrator forgot login password
Exomeiser annotates and prioritizes exome variants
Database learning – select (multi table joint query) [easy to understand]
[USENIX atc'22] an efficient distributed training framework whale that supports the super large-scale model of heterogeneous GPU clusters
Varnish4.0缓存代理配置
File upload and download and conversion between excel and data sheet data
[shaders realize pixelate mosaic effect _shader effect Chapter 7]
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)-- 第五题 树与二分图 (已完结)