When an Android app is becoming more and more powerful, communication between the various parts of the app is often done in a observer way, that is, registering----notification----logoff execution of various controls often requires updating the display based on a state. The common solution to this scenario is to define an interface that needs to be focused on the event's control to implement the interface. Interface class: Public interface Onchangedlistener {void Ondatachanged (); }
the observed are often implemented in the following form:
public abstract class Abshttprequest {private Final Weakhashmap<onchangedlistener, B oolean> mlisteners = new Weakhashmap<onchangedlistener, boolean> (); public interface Onchangedlistener {void ondatachanged (); }/*http ' s response*/public abstract void Onresponse (); Public final void AddListener (Onchangedlistener listener) {Mlisteners.put (listener, true); } public final void RemoveListener (Onchangedlistener listener) {mlisteners.remove (listener); } protected final void notifydatachanged () {set<onchangedlistener> keys = Mlisteners.keyset (); if (keys = null) {iterator<onchangedlistener> Iterator = Keys.iterator (); while (Iterator.hasnext ()) {Iterator.next (). ondatachanged (); } } }}
Specific subject role (the Observer ) , which is implemented in the following way:
public class Loginrequest extends Abshttprequest implements Onchangedlistener{public void Onresponse () {AddListener ( this); notifydatachanged ();} @Overridepublic void ondatachanged () {//TODO auto-generated method StubSystem.out.println ("Loginrequest");}}
One disadvantage of using the observer pattern is that the coupling between parts is too high, and all the subject roles need to implement the same interface. The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. The more observer a subject role is registered, the more interface you need to implement, and the more interface methods you will have.
How to decouple, make the code logic clearer, more readable, is a problem.
There is also a similar feature in Android, open Source Library Eventbus, it is very convenient to help us to implement the observer pattern, and to make the coupling between the various components less.
about the Eventbus of the article, the network industry a lot, here is recommended an article, explain the more detailed blog,http://www.cnblogs.com/angeldevil/p/3715934.htmlThe understanding of Eventbus, it is best to start from the demo, first easy after difficult. First know how to use, and then delve into the source code, in order to gradually, thoroughly understand one of the design concepts, convenient for future code debugging and Module reconstruction. On the demo, there are many online, you can check it yourself. the use of Eventbus has 4 stages:1. Define the event type:Public class MyEvent2. Registered Subscribers:Eventbus.getdefault (). Register (This)3. Send event:Eventbus.getdefault (). Post (New MyEvent ())4. Receiving events, processingThe function of the subscriber callback. Official guidance, the function name begins with OnEvent.
in the Eventbus module, there are several important concepts, after understanding these concepts, it is not difficult to understand.
Event: Can be any type of objectSubscriber: Subscribers, receiving a specificPublisher: Publisher, to notify subscriber senda parameter in the Eventtype:onevent function that represents the event object, which the user has customized. Subscriber: The subscription source, which is the object registered by the register, that contains the OnEvent member function.
Subscribmethod.javafinal class Subscribermethod { final method; The method member of the/*method type represents this onevent, the event handler function. It also includes a subscription source */ final threadmode Threadmode; Final class<?> EventType; /* The object of the event, user-defined object*/.................... ...}
Subscription.java
Final class Subscription { final Object subscriber; /* Subscribe to source Subscriber, which is called register registered Object */ final subscribermethod Subscribermethod;/**/ final int priority; ... ... ... ... ... ... ... ... ... ...}
in class Eventbus, there are two core members
/*eventtype, List<subscription> the mapping between events to subscribed objects */ private final map<class<?> Copyonwritearraylist<subscription>> Subscriptionsbyeventtype; /* subscriber, LIST<EVENTTYPE> a mapping relationship for all events subscribed to by the object, */ private final Map<object, list<class<? >>> Typesbysubscriber;
Registration process: when the register function is called, the Eventbus class has multiple overloaded register functions, but the author prefers to use register (this); In the register function with multiple parameters, Clearly marked the @deprecated, the original creator is not recommended to use. From code:
public void Register (Object subscriber) { Register (subscriber, Default_method_name, false, 0); }
It can be observed that all the overloaded register functions are called to the
Private synchronized void Register (Object subscriber, String methodName, boolean sticky, int priority) { list<subs cribermethod> subscribermethods = Subscribermethodfinder.findsubscribermethods (Subscriber.getClass (), MethodName); for (Subscribermethod subscribermethod:subscribermethods) { Subscribe (subscriber, Subscribermethod, sticky, priority); } }
which registers the function register, the default parameter default_method_name is the function name "OnEvent", in the Java emission mechanism, all the event handler function names are unified "OnEvent", only the parameters are inconsistent. The OnEvent parameter is a user-defined object.
When registering, use Subscribermethodfinder object, call to Findsubscribermethods method, get to list<subscribermethod>.
Array Object method[], called the GetMethods () method, gets all the common methods of the class, including all of its public methods, and all public methods inherited from the base class that are implemented from the interface. This is also why, our onevent function, to be defined as the reason for the public method Oh. in the Findsubscribermethods function, such frequent traversal is done in order to find list<subscribermethod>. each subscriber, corresponding to a list<subscribermethod>, how many onevent functions, and the list returned, is the number of item. that is to find the event handling method within the feed, and also to look up the event handling method in its parent class, return list, give
private void Subscribe (Object subscriber, Subscribermethod Subscribermethod, boolean sticky, int priority)
Be processed.
Between event and Subscriber is a one-to-many relationship. An event that can be followed by multiple subscribers.
Between subscriber and event is a one-to-many relationship. That is, a subscriber can subscribe to multiple events.
Subscribe method, that is, the above-mentioned relationship, to rationalize the mapping of a reasonable map of the relationship, mainly to do such a few events.
A.Subscribtion objects are stored in Subscriptionsbyeventtype according to the EventType type in Subscribermethod. Establish mappings between EventType and subscription, where an event can have multiple subscribers.
B.Based on subscriber, EventType is stored in Typesbysubscriber ', which establishes subscriber to eventtype mappings, and each Subscriber can subscribe to multiple events.
c.If it is a sticky type of subscriber, send it the last saved event (if any) directly to it.
With the subscriber-to-eventtype mapping, we can easily make a subscriber cancel the receive event, through the EventType to the Sucscribtion map, it is convenient to send the corresponding event to each of its subscribers.
Unlike Observer, using Eventbus, different observers, do not need to implement the interface method in Observer, in the upper code, there is no notify mechanism. The correspondence between feeds and event functions is decoupled, which is the core of the map.
Sending process:
Eventbus.getdefault (). Post (New EventType ()); The parameter is a user-defined object. the simplest way to handle events is to send them.
when the event is sent out, how do all Subscribers invoke their event methods? This will need to traverse the Subscriptionsbyeventtype map mentioned above. Post sends an event, the entry is a post function: public void post (Object event), in the Postsingleevent function, there is an important processing function:
/** Finds all Class objects including super classes and interfaces. */ private list<class<?>> findeventtypes (class<?> eventclass) { synchronized ( Eventtypescache) { list<class<?>> eventtypes = Eventtypescache.get (EventClass); if (eventtypes = = null) { eventtypes = new arraylist<class<?>> (); class<?> clazz = EventClass; while (clazz! = null) { eventtypes.add (clazz); Addinterfaces (EventTypes, clazz.getinterfaces ()); Clazz = Clazz.getsuperclass (); } Eventtypescache.put (EventClass, eventtypes); } return eventtypes; } }
Its function is to put the object of this event class, the interface of implementation and the class object of the parent class into a list to return, according to the list of eventtypes, traverse the Subscriptionsbyeventtype, get the Feed object, make a call event function.
It is important to note that when an event is post, the parent event of the event (the event class's parent) and the interface event are also post, so if the Subscriber receives an event of type object, which contains the OnEvent (object object) event function, Then subscriber can receive all the events.
Through this blog post, Eventbus is to avoid the multiple, frequent definitions of observer interface methods by establishing the corresponding relationship between the feed and event functions through map and decoupling .
Android platform, Eventbus research Learning