当前位置:网站首页>Observer mode
Observer mode
2022-06-24 09:51:00 【Time202051】
// The theme newspaper office
class Subject {
constructor(name) {
this.name = name
this.news = "" // The contents published by the newspaper office , It will be published to all subscribers who have subscribed to the newspaper
this.observers = [] // User array
}
add(observer) {
this.observers.push(observer)
}
getState() {
return this.news
}
setState(news) {
this.news = news
// Publish a new newspaper , Publish to all users immediately
this.notify()
}
notify() {
this.observers.forEach(item => {
item.update(this) // Trigger... For all subscribers update
console.log('---------------');
})
}
}
// The observer user It is known that / Unknown users
class Observer {
constructor(name, subject) {
this.name = name // user name
this.subject = subject
this.subject.add(this) // Users give their information to newspapers ( Only then did the newspaper know who the subscribers were )
}
update(e) {
console.log(this.subject.name+" To the messenger " + this.name + " Sent a newspaper with the content of : " + this.subject.getState());
}
}
// One to many A newspaper office corresponds to multiple users
let bs = new Subject(' The xinhua news agency ')
let lts = new Subject(" (Reuters) - ")
let zs = new Observer(' Frenchman Zhang San ', bs)
let ls = new Observer(" Li Si ", bs) // Li Si also subscribed to the newspaper
let ww = new Observer(" Wang Wu ", bs) // Wang Wu also subscribed to the newspaper
let zl = new Observer(" Zhao Liu ",lts)
let mq = new Observer(" Horse seven ",lts)
// Newspapers publish newspapers
let new1 = bs.setState(" Hello, everyone. I'm a newspaper , Thank you for subscribing to our newspaper ")
let new2 = bs.setState(" The first issue of the newspaper office ")
let ltsNew1 = lts.setState(" Here is the latest Reuters report ")
console.log(new1);
console.log(new2);
console.log(ltsNew1);
边栏推荐
猜你喜欢

生产者/消费者模型

PTA monkey chooses King (Joseph Ring problem)

居家办公如何管理数据中心网络基础设施?

LeetCode: 240. 搜索二维矩阵 II

ByteDance Interviewer: talk about the principle of audio and video synchronization. Can audio and video be absolutely synchronized?

latex公式及表格识别

js单例模式

SSH Remote Password free login

Servlet fast foundation building

tp5 使用post接收数组数据时报variable type error: array错误的解决方法
随机推荐
Use of vim
百度AI模板 获取知识理解
June 13-19, 2022 AI industry weekly (issue 102): career development
Oracle的tnsnames.ora文件配置
Conseils étonnants pour promouvoir les ventes d'entreprise avec le chat en direct
正则匹配邮箱
Directly applicable go coding specification
获取带参数的微信小程序二维码-以及修改二维码LOGO源码分享
正则匹配手机号
新手怎么选择投资理财产品的等级?
How to locate lock waiting in Dameng database
el-table表格的拖拽 sortablejs
如何规范化数据中心基础设施管理流程
NLP-D59-nlp比赛D28—我想,也好—阶段总结—心态调整
LeetCode: 240. 搜索二维矩阵 II
文献调研报告
Ora-28000 error after upgrading Oracle 12C to 19C
JCIM|药物发现中基于AI的蛋白质结构预测:影响和挑战
php单例模式详解
Oracle数据库监听文件配置