当前位置:网站首页>观察者模式
观察者模式
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);
边栏推荐
- Reasons for the failure of digital transformation and the way to success
- Detailed explanation of ThinkPHP 5.0 Model Association
- Amendment to VPP implementation policy routing
- Oracle的tnsnames.ora文件配置
- June 13-19, 2022 AI industry weekly (issue 102): career development
- 二十、处理器调度(RR时间片轮转,MLFQ多级反馈队列,CFS完全公平调度器,优先级翻转;多处理器调度)
- Algorithm - the K row with the weakest combat power in the matrix (kotlin)
- Directly applicable go coding specification
- ThinkPHP 5.0 模型关联详解
- Endgame P.O.O
猜你喜欢

Prct-1400: failed to execute getcrshome resolution

最新Windows下Go语言开发环境搭建+GoLand配置

LeetCode: 240. 搜索二维矩阵 II

June 13-19, 2022 AI industry weekly (issue 102): career development

Summary of medical image open source datasets (II)

ApplicationContextInitializer的三种使用方法

生产者/消费者模型

Handling method of Oracle data file header SCN inconsistency

使用Live Chat促进业务销售的惊人技巧

Grpc local test joint debugging tool bloomrpc
随机推荐
如何让社交媒体成为跨境电商驱动力?这款独立站工具不能错过!
如何规范化数据中心基础设施管理流程
In depth analysis of Apache bookkeeper series: Part 3 - reading principle
Analysis of 43 cases of MATLAB neural network: Chapter 32 time series prediction of wavelet neural network - short-term traffic flow prediction
生产者/消费者模型
字节跳动-面试官: 谈下音视频同步原理,音频和视频能绝对同步吗?
五心红娘
PHP使用递归和非递归方式实现创建多级文件夹
Weekly recommended short video: talk about "meta universe" with a serious attitude
[bug] @jsonformat has a problem that the date is less than one day when it is used
Codeforces Round #392 (Div. 2) D. Ability To Convert
Niuke.com string deformation
什么情况下应该使用GridFS?
LeetCode: 377. 组合总和 Ⅳ
PostgreSQL
ThinkPHP 5.0 模型关联详解
《MATLAB 神经网络43个案例分析》:第32章 小波神经网络的时间序列预测——短时交通流量预测
PostgreSQL DBA快速入门-通过源码编译安装
Talking about the knowledge of digital transformation
Grpc local test joint debugging tool bloomrpc