"Android Translator" component communication mode

Source: Internet
Author: User
Tags eventbus

Objective: Avoid tight coupling

In this paper, the original text is streamlined

Original link: Communication Patterns for application components

Tight coupling

The components hold references to each other and call methods directly. In the following code, Menufragment holds a direct reference to magazineactivity, so menufragment is tightly coupled with magazineactivity.
Once there is no magazineactivity, you will not be able to work.

// 紧耦合示例class MenuFragment extends Fragment {    private void onArticleClick(int articleId) {        MagazineActivity magAct = (MagazineActivity) getActivity();        magAct.showArticle(articleId);    }}

In such a design, the modification of a class may affect a large wave of related classes, and if it involves more than one developer in development, then this situation will only bring pain and sorrow.

The core of loose coupling is to reduce the dependency between components, a loosely coupled system can be easily decomposed into well-structured elements. This makes the system more resilient and scalable.
Each developer can maintain a separate module and communicate with other parts using standard protocols.

General Decoupling method: interface

(Personal supplement: The interface is not simply referring to the interface keyword in Java, but rather a message specification/protocol)
An interface is a powerful decoupling tool: a class can communicate through an interface without having to refer directly to another specific class. A class can provide an interface to other classes to communicate with. At this level of abstraction, other classes don't care what the specific implementation is.

//接口示例class MenuFragment extends Fragment {    public static MenuFragment instantiate(ArticleSwitcher articleSwitcher) {        MenuFragment menuFragment = new MenuFragment();        menuFragment.articleSwitcher = articleSwitcher;        return menuFragment;    }    ArticleSwitcher articleSwitcher;    public void onArticleClick(int articleId) {        articleSwitcher.showArticle(articleId);    }}

Disadvantages of using interfaces:

    1. Components still need to know each other to pass the interface, some dependencies still exist
    2. Interface cannot be passed through intent
    3. In large projects, the number of interfaces increases sharply, resulting in a large number of template code
    4. Interface chains are formed when interfaces are passed between components, resulting in increased complexity
Elegant Solution: Message bus

Communication scenarios based on the publish/subscriber pattern. The publisher publishes a notification, the Subscriber is notified and responds, so the publisher and the Subscriber are decoupled from the implementation.

Implementing the Message BusImplicit Intent + Broadcastreceiver

Communication through implicit intent can be thought of as a form of Message Queuing:
Sendbroadcast (Intent) or startactivity (Intent) is a Publisher method that contains intentfilter or activity that plays the role of the Subscriber.

Advantages and Disadvantages

Pros: It can be passed across apps and is the standard method inside Android

Cons: Unable to deliver complex data, must pass through bundles

Fluffyevents is a message bus that is implemented through Broadcastreceiver.

Eventbus: Event-based message bus

(The "event" itself is also a message, the principle is the subscription/publisher mode)

The event itself can be any Java class, as follows:

// 一个示例事件类class DownloadProgressEvent {    private float progress;    public DownloadProgressEvent(float progress) {        this.progress = progress;    }    public float getProgress() {        return progress;    }}
Eventbus: General principles

Eventbus uses the appropriate data structure to maintain events and subscribers ' correspondence, such as the way Otto uses them:

/** Cache event bus subscriber methods for each class. */private static final Map<Class<?>, Map<EventClass, Set>> SUBSCRIBERS_CACHE = new HashMap<Class<?>, Map<EventClass, Set>>();

Each time a subscriber registers or logs off, the corresponding relationship will be updated at the same time, usually, Activity or fragment will be registered in the Onresume phase, in the onpause phase of the logoff. (Translator Note: Can reduce the problem of memory leakage)

Whenever an event is published, Eventbus iterates through the entire correspondence, finds all eligible subscriber methods, and executes.

Sticky Event

Like Android native Stickybroadcast, this event is available for a subscriber to register at any time.

Summarize

Because Eventbus is not an intrinsic mechanism of Android, it is not possible to pass events across apps.

More commonly used two Eventbus open source class libraries:

Square's Otto: Based on annotations, optimized for the Android platform on the basis of guava Eventbus

Greenrobot ' s Eventbus: A better thread distribution mechanism.

(Translator Note: Eventbus is more suitable for decoupling between components, and interfaces are a more abstract concept and can also be used in view or other aspects)

Android Share Q Group: 315658668

"Android Translator" component communication mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.