当前位置:网站首页>观察者模式
观察者模式
2022-08-01 12:38:00 【51CTO】
《Head First Design Pattern》一书中对观察者模式的定义如下:
The Observer Pattern defines a one-to-many dependency objects so that when one object changes state, all of its dependents are notified and updated automatically.
观察者设计模式定义了对象间的一种一对多的依赖关系,以便一个对象的状态发生变化时,所有依赖于它的对象都得到通知并自动刷新。
从根本上说,该模式必须包含两个角色:观察者和被观察对象。下面是设计模式中包含角色的UML类图(来自百度百科)。
观察者(Observer)将自己注册到被观察对象(Subject)中,被观察对象将观察者存放在一个容器(Container)里。
被观察对象(Subject)发生了某种变化,从容器中得到所有注册过的观察者,将变化通知观察者。
下面举这样一个例子:比如一个小游戏,A说出一个十进制的数,B说出其对应的二进制结果,C说出其对应的八进制结果,D说出其对应的十六进制结果。
使用观察者模式A可以作为被观察者(Subject),B、C、D可以作为观察者(Observer)。
下面是Java代码示例:
观察者接口:
被观察者接口:
实体被观察者A:就是游戏中的A
实体观察者B:游戏中的B,将A给的数字转成二进制
实体观察者D:游戏中的D,将A给的数字转成十六进制
观察者模式测试代码:我们开始做游戏了
运行结果:
其实Java JDK本身提供了设计模式等额实现:
java.util.Observer是一个接口,观察者接口,相当于我们上面的IObserver接口。我们需要实现一个观察者的时候只需要实现这个接口就OK了。
java.util.Observable是一个类,被观察者类,我们需要实现一个被观察者的时候只需要继承这个类就OK了。
边栏推荐
- How do programmers solve online problems gracefully?
- Simulation implementation of new of Js handwritten function
- Meshlab & Open3D SOR filtering
- 【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用
- Audio and Video Technology Development Weekly | 256
- CloudCompare & PCL ICP registration (point to face)
- R language fitting ARIMA model: use the auto.arima function in the forecast package to automatically search for the best parameter combination, model order (p, d, q), set the seasonal parameter to spe
- Meshlab&Open3D SOR滤波
- 如何成功通过 CKA 考试?
- Data frame and remote frame of CAN communication
猜你喜欢
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
程序员如何优雅地解决线上问题?
2022 Go ecosystem rpc framework Benchmark
The CAN communication standard frame and extended frame is introduced
一文带你读懂云原生、微服务与高可用
[Open class preview]: Research and application of super-resolution technology in the field of video quality enhancement
故障007:dexp导数莫名中断
Process sibling data into tree data
HMS Core音频编辑服务音源分离与空间音频渲染,助力快速进入3D音频的世界
【讲座分享】“营收“看金融
随机推荐
程序员的自我修养
LeetCode_动态规划_中等_377.组合总和 Ⅳ
动态库、静态库浅析
CAN通信标准帧和扩展帧介绍
windows IDEA + PHP+xdebug 断点调试
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
The four methods of judging JS data type
LeetCode_位运算_简单_405.数字转换为十六进制数
SQL函数 %SQLUPPER
Favorites|Mechanical Engineer Interview Frequently Asked Questions
[Cloud Enjoying Freshness] Community Weekly Vol.73- DTSE Tech Talk: 1 hour in-depth interpretation of SaaS application system design
[Community Star Selection] Issue 24 August Update Plan | Keep writing, refuse to lie down!More original incentive packages, as well as Huawei WATCH FIT watches!
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
LeetCode_动态规划_中等_313.超级丑数
Js手写函数之new的模拟实现
SQL function SQRT
How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!
Software designer test center summary (interior designer personal summary)
Fault 007: The dexp derivative is inexplicably interrupted
【云享新鲜】社区周刊·Vol.73- DTSE Tech Talk:1小时深度解读SaaS应用系统设计