当前位置:网站首页>(JS) observer mode
(JS) observer mode
2022-06-29 11:03:00 【Yu Cainiao, who asked not to be named】
(JS) Observer mode
One to many
Release & subscribe
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
this.notifyAllObservers();
}
// Trigger every Observer Of update() Method
notifyAllObservers() {
this.observers.forEach(observer => {
observer.update();
});
}
// Add each new observer All added this.observers in
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
边栏推荐
- math_数学表达式&等式方程的变形&组合操作技巧/手段积累
- (JS)手写bind函数
- Shell 中你不得不熟知的变量运用
- Nuc980 open source project 16- start from SPI flash (w25q128)
- Does your project need automated testing?
- (JS)isNaN()方法判断undefined为true的原因
- 嵌入式驱动开发之uboot---uboot 中的常见命令参数参数
- Memory allocation - static storage stack heap and static variable
- 【C语言进阶】通讯录实现
- crypto 1~5
猜你喜欢
随机推荐
[digital signal modulation] realize signal modulation and demodulation based on am+fm+dsb+ssb, including Matlab source code
Summary after reading how to read a Book
dropout层
励志!专科“逆袭”读浙大硕士,3篇SCI,最终成清华博士!
(JS)职责链模式
基于支持向量机的手写数字识别详解(MATLAB GUI代码,提供手写板)
反CSRF爆破的三种姿势
【数字信号调制】基于 AM+FM+DSB+SSB实现信号调制解调含Matlab源码
Daily question brushing record (VII)
《Datawhale推荐系统教程》来了!
(JS)isNaN()方法判断undefined为true的原因
当技术人成长为 CEO,应该修改哪些“Bug”?
Qt编写物联网管理平台37-逻辑设计
TTL串口学习型红外遥控模块可扩展成网络控制
arcgis创建postgre企业级数据库
BS-GX-017基于SSM实现的在线考试管理系统
(JS)数组去除重复
Please tell me about the Flink SQL batch task, two or more tables join (inner join or outer join
期未课程设计:基于SSM的产品销售管理系统
【C语言进阶】字符串和内存函数(一)









