观察者模式之EventBus源码解析

1、观察者模式概述:

观察者模式(Observer Pattern):定义对象之间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并自动更新。观察者模式的别名包括发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式。观察者模式是一种对象行为型模式《设计模式的艺术》

使用场景:

观察者模式是使用频率最高的设计模式之一,主要用于建立对象之间的一种一对多的依赖关系。通过发布订阅的方式,实现对象之间的解耦合。主要用于当一个对象状态改变时,另外一个对象会随之变化的场景。一个目标可以对于多个观察者,各个观察者之间互不联系,只关注目标状态的改变。

2、代理模式UML类图:

image.png

Subject(抽象目标类):目标又称之为主题,它是指被观察的对象。在抽象目标类中会定义一个抽象观察者的集合,并定义增加和删除、通知观察者的相关接口。
ConcreteSubject(具体目标):作为抽象目标类的子类,实现抽象目标类定义的接口。当具体目标状态发生变化时,通过观察者。
Observer(抽象观察者):所谓所有观察者的公共父类,定义观察者的共同行为接口。
ConcreteObserver(具体观察者):作为抽象观察者的子类,实现相关接口,当收到具体目标状态改变的通知,执行具体业务逻辑。

3、EventBus源码分析:

EventBus是Android平台下用于应用内各组件或者模块间通信的一个类库,其主要实现思想为观察者模式。

//以下代码为观察者注册和监听的相关代码
class TestActivity: Activity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //注册该Activity为观察者
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        //注销注册
        EventBus.getDefault().unregister(this)
    }
    //接收通知方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(message: String?) {
        Log.i("TestActivity", "receive a message is $message")
    }
}

class MainActivity : BaseActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_main)
        //发送消息        
        EventBus.getDefault().post("send message")
    }
}
  //Eventbus源码,观察者注册过程
    public void register(Object subscriber) {
        Class subscriberClass = subscriber.getClass();
        //寻找类中的订阅方法(通过Subscribe注解)
        List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //拿到类中带有Subscribe注解的方法后,将该类注册为观察者
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    List findSubscriberMethods(Class subscriberClass) {
        List subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {
           //通过反射方法拿到类中方法的注解信息
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
    //下述subscribribe方法才是真正的注册观察者方法
    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                //将该类对应的subscription对象加入到监听站集合中
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        List> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super classes: Class -> List).
                Set, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry, Object> entry : entries) {
                    Class candidateEventType = entry.getKey();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }
    
    /** Posts the given event to the event bus. */
    public void post(Object event) {
        //先将该时间加入到队列
        PostingThreadState postingState = currentPostingThreadState.get();
        List eventQueue = postingState.eventQueue;
        eventQueue.add(event);

        if (!postingState.isPosting) {
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }
    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            List> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class clazz = eventTypes.get(h);
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }
    //最终调用的方法
    void invokeSubscriber(Subscription subscription, Object event) {
        try {
            //通过反射调用监听者的方法
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }
 
 

EventBus的设计充分体现观察者模式的思想,消息发布者与订阅者之间充分解耦合。接口实现灵活度高,EventBus类作为整个库的核心,完成订阅与发布的功能,使得目标与观察者能够很好的通信。此外,观察者模式应用于MVC架构上,实现表示出与数据逻辑层的分离。

4、优缺点分析:

优点:

1)在观察者和目标之间解耦合;
2)支持广播通信,简化一对多系统设计;
3)符合开闭原则,扩展性好;

缺点:

1)目标状态改变时,会将变化通知到所有观察者,时间消耗较大;

结束语

观察者模式作为一种很常用和实用的设计模式,常在广播实现、MVC等架构上应用。对于降低系统耦合下,提高系统的扩展性很有用。一对多关系的模型较适合使用。

你可能感兴趣的:(观察者模式之EventBus源码解析)