当前位置:网站首页>观察者模式
观察者模式
2022-06-24 09:32:00 【Time202051】
// 主题 报社
class Subject {
constructor(name) {
this.name = name
this.news = "" //报社发布的内容,将会发布给所有已订阅报纸的用户
this.observers = [] //用户数组
}
add(observer) {
this.observers.push(observer)
}
getState() {
return this.news
}
setState(news) {
this.news = news
// 出版新报纸,立刻发布给所有用户
this.notify()
}
notify() {
this.observers.forEach(item => {
item.update(this) //触发所有订阅用户的update
console.log('---------------');
})
}
}
// 观察者 用户 已知/未知用户们
class Observer {
constructor(name, subject) {
this.name = name //用户名
this.subject = subject
this.subject.add(this) //用户将自己信息给报社(报社才知道谁是订阅用户)
}
update(e) {
console.log(this.subject.name+" 送报员给 " + this.name + " 送了份报纸内容是: " + this.subject.getState());
}
}
// 一对多 一家报社对应多个用户
let bs = new Subject('新华社')
let lts = new Subject("路透社")
let zs = new Observer('法外狂徒张三', bs)
let ls = new Observer("李四", bs) //李四也订阅了报社
let ww = new Observer("王五", bs) //王五也订阅了报社
let zl = new Observer("赵六",lts)
let mq = new Observer("马七",lts)
// 报社发布报纸
let new1 = bs.setState("大家好我是报社,谢谢大家订阅我们报社")
let new2 = bs.setState("报社第一期内容")
let ltsNew1 = lts.setState("这里是路透社最新报道")
console.log(new1);
console.log(new2);
console.log(ltsNew1);
边栏推荐
- Threejs point light + ambient light
- e的lnx为什么等于x
- vim的使用
- SQL-统计连续N天登陆的用户
- Oracle viewing data file header SCN information
- Analysis of 43 cases of MATLAB neural network: Chapter 32 time series prediction of wavelet neural network - short-term traffic flow prediction
- Amazing tips for using live chat to drive business sales
- leetcode--链表
- June 13-19, 2022 AI industry weekly (issue 102): career development
- CF566E-Restoring Map【bitset】
猜你喜欢
随机推荐
[custom endpoint and implementation principle]
Learn Tai Chi Maker - esp8226 (12) esp8266 multitasking
5分钟,客服聊天处理技巧,炉火纯青
latex公式及表格识别
正则匹配手机号
198. 打家劫舍
LeetCode: 137. Number II that appears only once
使用Live Chat促進業務銷售的驚人技巧
In depth analysis of Apache bookkeeper series: Part 3 - reading principle
Zero foundation self-study SQL course | sub query
买的长期理财产品,可以转短吗?
Go language project development practice directory
二十、处理器调度(RR时间片轮转,MLFQ多级反馈队列,CFS完全公平调度器,优先级翻转;多处理器调度)
An open source monitoring data collector that can monitor everything
Cdga | how can we do well in data governance?
Thinkphp5 multi language switching project practice
Servlet fast foundation building
grpc本地测试联调工具BloomRPC
Honeypot 2 hfish, ehoney
编程题(持续更新)









