当前位置:网站首页>(JS)观察者模式
(JS)观察者模式
2022-06-29 09:57:00 【不愿透露姓名的余菜鸟】
(JS)观察者模式
一对多
发布&订阅
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
this.notifyAllObservers();
}
// 触发每一个Observer的update()方法
notifyAllObservers() {
this.observers.forEach(observer => {
observer.update();
});
}
// 将每个新建的observer都添加进this.observers中
attach(observer) {
this.observers.push(observer);
}
}
class Observer {
constructor(name, subject) {
this.name = name;
this.subject = subject;
this.subject.attach(this);
}
update() {
console.log(`${
this.name} update,state:${
this.subject.getState()}`)
}
}
let sub = new Subject();
let o1 = new Observer("11", sub);
let o2 = new Observer("22", sub);
let o3 = new Observer("33", sub);
sub.setState(5)
11 update,state:5
22 update,state:5
33 update,state:5
边栏推荐
- 【C语言进阶】自定义类型
- 30-year-old female, ordinary software testing Yuanyuan, confused and anxious about her career
- Real test = "half product + Half development"?
- Comprehensive understanding of synchronized
- Given the values of two integer variables, the contents of the two values are exchanged (C language)
- Does anyone encounter this problem when flinkcdc synchronizes MySQL?
- AQS之ReentrantLock源码解析
- Ningde era Kirin battery has greater ambition
- CS231n-2022 Module1: 神经网络要点概述(2)
- Analysis of reentrantlock source code of AQS
猜你喜欢

Essential for efficient work: how can testers improve their communication skills?

C#MDI打开子窗体去掉自动生成的菜单栏

Stm32f1 and stm32subeide programming example - ultrasonic distance sensor drive

Dormitory maintenance management system based on stm32+rfid design

Atomic explanation of AQS

容器平台性能如何测试,稳定性、扩展效率、组件性能

最后的 48 小时!云 XR 专题赛邀你一起绽放精彩,我们赛场见!

【动态规划】—— 线性DP

Real test = "half product + Half development"?

高效工作必备:测试人如何提高沟通技能?
随机推荐
Here comes the tutorial of datawhale recommendation system!
常见电机分类和驱动原理动画[通俗易懂]
SQL Server 数据库的连接查询
【NLP】文本生成专题1:基础知识
你的项目需要自动化测试吗?
2600 pages in total! Another divine interview manual is available~
Software test model (V model and W model)
加密市场接连爆雷,Celsius能避免破产吗?
UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. 笔记
Qt编写物联网管理平台37-逻辑设计
AQS之Atomic详解
《MongoDB入门教程》第02篇 MongoDB安装
任职 22 年,PowerShell 之父将从微软离职:曾因开发 PowerShell 被微软降级过
VI退出 退出VIM 适用新手
(JS)数组排平(flat)
PyTorch学习笔记(6)——DataLoader源代码剖析
在 2022 年找工作,毕业生们的 “最后一课”
Does anyone encounter this problem when flinkcdc synchronizes MySQL?
dropout层
stream流(Collectors)用法