java 观察者模式Observable Observer
2016-05-19 15:55
375 查看
被观察者继承Observable 观察者实现Observer
过程:
1、调用Observable 的addObserver(Observer) 给被观察者添加观察者
2、在观察者Observer的update(Observable o, Object arg);的方法中做业务处理
3、调用Observable 的setChanged()方法把changed设置为true,调用notifyObservers()方法调用Observer的update方法
notifyObservers源码:
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
过程:
1、调用Observable 的addObserver(Observer) 给被观察者添加观察者
2、在观察者Observer的update(Observable o, Object arg);的方法中做业务处理
3、调用Observable 的setChanged()方法把changed设置为true,调用notifyObservers()方法调用Observer的update方法
notifyObservers源码:
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
相关文章推荐
- Cipher类_Java加密与解密的艺术
- Hibernate中的双向多对一关联以及 inverse属性、cascade属性的用法
- myeclipse中web工程的web-inf保护(初级篇)
- android eclipse无法检测到手机的解决方法
- spring中管理的类是否单例
- Java开发人员最常犯的10个错误
- java高效导出excel
- 2016最新spring包下载地址,绝对管用的spring资料。spring学习
- java通配符
- Java像素级的操作
- 暴力版java 吸血鬼数字 代码 --- 依靠循环嵌套解决。
- 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在
- SpringMVC学习系列-后记 解决GET请求时中文乱码的问题
- Extjs+SpringMvc 上传文件加进度条
- Spring技术内幕之IOC容器的实现(02)-BeanDefinition的Resource定位
- 搭建Spring MVC+JedisCluster集群
- Ubuntu 16.04 安装 JDK 和 Open Jdk
- java.util.AbstractCollection学习笔记
- java synchronized关键字
- Java的两种赋值的区别