定义:观察者模式定义了对象之间的一对多依赖,当一个对象的状态改变时,它的所有依赖者都会收到通知并更新。Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Copy package com . google . common . eventbus ;
public class EventBus {
private final SubscriberRegistry subscribers = new SubscriberRegistry( this ) ;
public void register ( Object object) {
subscribers . register (object);
}
public void unregister ( Object object) {
subscribers . unregister (object);
}
public void post ( Object event) {
Iterator < Subscriber > eventSubscribers = subscribers . getSubscribers (event);
if ( eventSubscribers . hasNext ()) {
dispatcher . dispatch (event , eventSubscribers);
} else if ( ! (event instanceof DeadEvent)) {
// the event had no subscribers and was not itself a DeadEvent
post( new DeadEvent( this , event)) ;
}
}
}
final class SubscriberRegistry {
private final ConcurrentMap < Class < ? > , CopyOnWriteArraySet < Subscriber >> subscribers =
Maps . newConcurrentMap ();
}