java实现观察者模式

javaapi中提供了两个类,可以帮助实现观察者模式
Observerable为发布者,Observer为订阅者
订阅者:发布者=1:1/1:n/n:m

import java.util.Observerable;
import java.util.Observer;
public class ObserverDemo {
public static void main(String[] args) {
    MyObservable myObservable = new MyObservable();
    myObservable.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object value) {
            System.out.println(value);
        }
    });
    myObservable.setChanged();//这里是Observerable源码有个判断,为false直接返回
    myObservable.notifyObservers("hello world");
}


public static class MyObservable extends Observable {
    public void setChanged() {
        super.setChanged();
    }
}
}
JDK源码
    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();
            }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值