当前位置:网站首页>(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
边栏推荐
- (JS)数组排平(flat)
- The encryption market has exploded one after another. Can Celsius avoid bankruptcy?
- UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. note
- 【评论送书】适合初学者的 6 个有趣的 R 语言项目
- 2600 pages in total! Another divine interview manual is available~
- 真正的测试 =“半个产品+半个开发”?
- Several methods of enterprise competition analysis: SWOT, Porter five forces, pest "suggestions collection"
- 小米手机-解BL锁+开ROOT权限
- 全面理解Synchronized
- Given the values of two integer variables, the contents of the two values are exchanged (C language)
猜你喜欢

高效工作必备:测试人如何提高沟通技能?

给定两个整形变量的值,将两个值的内容进行交换 (C语言)

当技术人成长为 CEO,应该修改哪些“Bug”?

悬赏平台并没有WEB端开发,在原生开发和混合开发中哪种合适?

Buuctf-- connotative software

STM32F1与STM32CubeIDE编程实例-超声波测距传感器驱动

UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. note

美国EB-5移民再现利好,区域中心再授权政策被叫停

ssh密钥泄露(B模块赛题)——应用服务漏洞扫描与利用

真正的测试 =“半个产品+半个开发”?
随机推荐
SQL Server 数据库的统计查询
JS post download file
【C语言进阶】动态内存管理
《如何阅读一本书》读后总结
Findbugs修改总结
Pytorch learning notes (6) -- source code analysis of dataloader
The difference between & & and &
CS231n-2022 Module1: 神经网络要点概述(2)
【Rust每周一库】Tokei - 统计代码行数等信息的实用工具
arcgis创建postgre企业级数据库
“AI x 科学计算”进行时,华为昇思 MindSpore 赛题火热开启,等你来!
企业竞争分析的几种方法:SWOT、波特五力、PEST「建议收藏」
【C语言进阶】文件操作(二)
Dormitory maintenance management system based on stm32+rfid design
Redis installation and cluster setup under Linux
智能组卷系统设计
反CSRF爆破的三种姿势
内存分配——静态存储区 栈 堆 与static变量
AQS之BlockingQueue源码解析
这个mySQL安装的时候怎么搞去了?