当前位置:网站首页>An article explaining the publisher subscriber model and the observer model
An article explaining the publisher subscriber model and the observer model
2022-07-01 02:51:00 【My name is pea】
difference
Observer mode : When there is a one to many dependency between objects , The state of one of the objects changes , All objects that depend on it will be notified , This is the observer model .
Publisher subscriber mode : Based on an event channel , Who wants to receive the notification Subscriber Subscribe to topics through custom events , The object of the activated event Publisher Notify subscribers of the topic by publishing the topic event Subscriber object .
The observer pattern is , When the observed data changes , Call the observer's notify Method , To inform all observers to perform update Method to update . For publisher subscriber mode , First of all, publishers and subscribers don't know each other's existence , They are dispatched through the event center , The publisher publishes a corresponding event topic in the event center , Subscribers subscribe to an event body in the event center , When the subscriber triggers emit Execute the events published by the publisher .
Vue A case showing its design pattern ,Vue Our two-way data binding uses the observer pattern , Its event bus EventBus The publisher subscriber mode is used .
Realization
Handwritten publisher subscriber mode
class EventEmitter {
constructor() {
this.events = {
}
}
on(name, fn) {
if (this.events[name]) {
this.events[name].push(fn)
} else {
this.events[name] = [fn]
}
}
off(name, fn) {
this.events[name] = this.events[name].filter(event => event != fn)
}
once(name, fn) {
let one = (...args) => {
fn(...args)
this.off(name, one)
}
this.on(name, one)
}
emit(name, ...args) {
this.events[name].forEach(event => {
event.apply(this, args)
})
}
}
let ev = new EventEmitter()
let func = function () {
console.log(" I'm Xiao Liu ")
}
ev.on("name",func)
ev.once("name1", function () {
console.log(" I'm Xiao Li ")
})
ev.emit("name1")
ev.emit("name")
// Log off the corresponding event
ev.off("name", func)
// Trigger the corresponding event
ev.emit("name")
Handwriting observer mode
// Observed target , Publisher :Dep
// Observed target , Publisher :Dep
class Dep {
constructor() {
// Record all observers , Subscribers
this.subs = []
}
// Add a new observer
addSub(sub) {
// The subscriber exists and has update Method , Just add it to subs Array
if (sub && sub.update) {
this.subs.push(sub)
}
}
// Remove observer
removeSub(sub) {
if (this.subs.length) {
let index = this.subs.indexOf(sub)
if (index > -1) {
this.subs.splice(index, 1)
}
}
}
// Publish update notification
notify() {
this.subs.forEach(item => {
item.update()
})
}
}
// The observer , Subscribers
class Watcher {
update() {
console.log("**** Update relevant data ****")
}
}
let dep = new Dep
let watcher1 = new Watcher()
let watcher2 = new Watcher()
// Add a new observer
dep.addSub(watcher1)
dep.addSub(watcher2)
dep.removeSub(watcher2)
// Release
dep.notify()
边栏推荐
- LeetCode_栈_困难_227.基本计算器(不含乘除)
- 鼠标悬停效果八
- Pycharm 打开远程目录 Remote Host
- Why are strings immutable in many programming languages? [repeated] - why are strings immutable in many programming languages? [duplicate]
- Codeforces Round #416 (Div. 2) C. Vladik and Memorable Trip
- Network address translation (NAT) technology
- Densenet network paper learning notes
- 园区运营效率提升,小程序容器技术加速应用平台化管理
- Pychar open remote directory remote host
- Ipmitool download address and possible problems during compilation and installation
猜你喜欢

Evaluation of the entry-level models of 5 mainstream smart speakers: apple, Xiaomi, Huawei, tmall, Xiaodu, who is better?

Share Creators萌芽人才培养计划来了!

How to use Jieba participle in unity

Applet custom top navigation bar, uni app wechat applet custom top navigation bar

园区运营效率提升,小程序容器技术加速应用平台化管理

Detailed explanation of pointer array and array pointer (comprehensive knowledge points)

AI 边缘计算平台 - BeagleBone AI 64 简介

Xception learning notes

js中的图片预加载

Zero foundation self-study SQL course | window function
随机推荐
7_ Openresty installation
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
The mobile edge browser cannot open the third-party application
js 找出两个数组中的重复元素
Why are strings immutable in many programming languages? [repeated] - why are strings immutable in many programming languages? [duplicate]
如果在小券商办理网上开户安全吗?我的资金会不会不安全?
Pulsar geo replication/ disaster recovery / regional replication
PTA 1016
Résumé des styles de développement d'applets Wechat
鼠标悬停效果三
Share Creators萌芽人才培养计划来了!
servlet【初识】
Cluster method synchronous execution framework suona
Desai wisdom number - other charts (parallel coordinate chart): employment of fresh majors in 2021
Contrastive learning of Class-agnostic Activation Map for Weakly Supervised Object Localization and
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(下)
CentOS installs multiple versions of PHP and switches
SAP ALV汇总跟导出Excel 汇总数据不一致
Pulsar的Proxy支持和SNI路由
Share Creators萌芽人才培養計劃來了!