当前位置:网站首页>观察者模式
观察者模式
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 to get the address of WeChat video account (link address of WeChat public account)
- 意大利普拉托华社将游行示威 盼解决安全问题
- Aeraki Mesh became CNCF sandbox project
- 收藏|机械工程师面试常问问题
- Fault 007: The dexp derivative is inexplicably interrupted
- How to Integrate Your Service Registry with Istio?
- 硬链接、软连接浅析
- 数字证书原理
- 英特尔全方位打造算力基础,助推“算”赋百业
- 安全又省钱,“15岁”老小区用上管道燃气
猜你喜欢
音视频技术开发周刊 | 256
故障007:dexp导数莫名中断
MarkDown公式指导手册
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 image quality enhancement
Feign 从注册到调用原理分析
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
Excel表格打印时不打印标记填充颜色
随机推荐
AI目标分割能力,无需绿幕即可实现快速视频抠图
kubernetes之DaemonSet以及滚动更新
bat倒计时代码
Tencent Cloud Native: Service Mesh Practice of Areaki Mesh in the 2022 Winter Olympics Video Live Application
Do wildcard SSL certificates not support multiple domains?
库函数的模拟实现(strlen)(strcpy)(strcat)(strcmp)(strstr)(memcpy)(memmove)(C语言)(VS)
MarkDown公式指导手册
[Unity3D Plugin] AVPro Video Plugin Share "Video Player Plugin"
R语言拟合ARIMA模型:使用forecast包中的auto.arima函数自动搜索最佳参数组合、模型阶数(p,d,q)、设置seasonal参数指定在模型中是否包含季节信息
重磅消息 | Authing 实现与西门子低代码平台的集成
bat countdown code
浏览器存储
一文带你彻底厘清 Isito 中的证书工作机制
Software designer test center summary (interior designer personal summary)
[Nodejs] fs module of node
批量任务导入到数据库中
Favorites|Mechanical Engineer Interview Frequently Asked Questions
安装apex报错
How do programmers solve online problems gracefully?
Qt get all files in a folder