当前位置:网站首页>(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
边栏推荐
- 基于STM32+RFID设计的宿舍检修管理系统
- 励志!专科“逆袭”读浙大硕士,3篇SCI,最终成清华博士!
- 【动态规划】—— 线性DP
- 有人遇到FlinkCdc同步MySQL时候出现的这个问题吗?
- Common motor classification and driving principle animation [easy to understand]
- 悬赏平台并没有WEB端开发,在原生开发和混合开发中哪种合适?
- 30岁,女,普通软件测试媛,对职业的迷茫和焦虑
- 内存分配——静态存储区 栈 堆 与static变量
- Here comes the tutorial of datawhale recommendation system!
- Xiaomi mobile phone - Unlock BL + open root permission
猜你喜欢
随机推荐
Cs231n-2022 module1: overview of key points of neural network (2)
Is it safe to open a securities account? Is it reliable?
By asp Net core downloading files according to the path
基于STM32+RFID设计的宿舍检修管理系统
AQS之BlockingQueue源码解析
基于支持向量机的手写数字识别详解(MATLAB GUI代码,提供手写板)
Print 9*9 multiplication formula table (C language)
智能组卷系统设计
UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. note
Highly paid programmers & interview questions: how to ensure the data consistency between redis cache and database in series 117?
Automatic 3D Detection and Segmentation of Head and Neck Cancer from MRI Data.
【Rust每周一库】Tokei - 统计代码行数等信息的实用工具
Report card of regional industrial Internet market, the second place of Baidu intelligent yunkaiwu
【C语言进阶】自定义类型
The difference between & & and &
# 【OpenCV 例程200篇】214. 绘制椭圆的参数详解
Ora-01950 does not have permission on tablespace
Memory allocation - static storage stack heap and static variable
Design of intelligent test paper generation system
The product strength is not inferior to that of BYD. Geely Dihao l Raytheon hi · x delivered 10000 units in the first month









