On the development of Android application layer with MVP

Source: Internet
Author: User

PS One sentence: Eventually choose Csdn to organize the publication of the knowledge points of these years, the article parallel migration to CSDN. Because CSDN also support markdown grammar, Ah!

"Artisan Joshui Http://blog.csdn.net/yanbober"

background

The reason to talk about this topic is because you may find in the development of the app, the responsibility of the activity is very heavy, if you stand in the MVC framework to see your own development of the app, the General XML Layout file section activity of the Setcontentview and so on as the view role, The activity other code acts as the controller role, and other data sources (databases, etc.) act as model roles. So you will find that the activity goes against the principle of single responsibility and is overburdened. Also, if you are testing the logical data layer, you will find it difficult to write test cases. In this way, is there a decoupling method?

Yes, that's the MVP framework.

MVP Architecture

MVP is Model-view-presenter. You don't have to do a lot of explaining, as shown here you can understand roughly:

The following three elements are required to see the MVP pattern as shown:

    1. The left-most view. That is, activity in Android. Also need to create a view of the abstract interface view interface. A view-implemented interface is required, and the view interacts with the presenter through the view interface to reduce coupling.
    2. The right-most model. Used to perform actual data (e.g. data storage, etc.). Sometimes it is also necessary to create a model of the abstract interface model interface to reduce coupling.
    3. The middle of the presenter. As an intermediate link between view and model, handles the responsible logic for interacting with the user.
program Ape's Tangled-MVP and MVC

After reading the above two paragraphs, you may wonder about the MVP, and an MVC, what's his relationship?

Then look at MVC again!

MVC architecture

The MVC framework believes that the software can be divided into three parts as follows:

    • View: User interface.
    • Controller: Business logic.
    • Model: Data save.

The core of the MVC framework is shown visually:

After the view transfer instruction to Controller,controller completes the business logic, the model changes the state, the model sends the new data to the view, and the user gets feedback.

MVP vs. Mvc

At this point you will find that MVC and the MVP of the structure of the chart are very different, the specific difference is as follows:

MVP Architecture:

View does not interact directly with the model, but interacts with the model indirectly by interacting with the presenter.
The interaction between presenter and view is done through an interface.
The view is usually one-to-presenter, but complex view may bind multiple presenter to handle logic.

MVC Architecture:

View can interact directly with the model.
The controller is behavior-based and can be shared by multiple view.
It is up to you to decide which view to display.

Summarize

MVC is very similar to MVP, but there are a lot of differences, and there are different points of view that stand on different angles of analysis, and this is just the result of the analysis based on the Android app code.

MVP architecture for Android apps:

Full engineering code point I go to the download page

background: The following example simulates the process of user interactive access to data, the user enters the data and then clicks Save, and then clicks get data to get the data saved by the operation.
UI Interface:

project directory structure:

Detailed code:

First look at the model layer code, the model layer provides an abstract interface, convenient decoupling, and convenient test case test model of the IMPL implementation code. The abstract interface and implementation code are shown below.

Model Layer Abstract Interface:

publicinterface IInfoModel {    //从数据提供者获取数据方法    InfoBean getInfo();    //存入数据提供者方法    void setInfo(InfoBean info);}

Model Layer Abstract Implementation:

public  class  infomodelimpl  implements  iinfomodel  { //simulated storage data  private  infobean infobean = new  Infobean ();  @Override  public  Infobean getinfo  () {//simulated storage data, real many actions   return Infobean; }  @Override  public  void  setinfo  (Infobean info) { //Simulation Store the data, there is a lot of real action  Infobean = info; }} 

Then look at the view layer code, the view layer also provides an abstract interface, convenient decoupling, and convenient test case Test View IMPL implementation of interactive code. The code for the abstract interface is shown below.

Abstract interface for the view layer:

publicinterface IInfoView {    //给UI显示数据的方法    void setInfo(InfoBean info);    //从UI取数据的方法    InfoBean getInfo();}

This time in fact you can think of, write UI and logic of the people can be completely divided, they interface through interfaces. Presenter's role is more like an adapter class for design patterns, which is responsible for interfacing UI with data logic. So let's take a look at the implementation of presenter:

 Public  class Presenter {    PrivateIinfomodel Infomodel;PrivateIinfoview InfoView; Public Presenter(Iinfoview InfoView) { This. InfoView = InfoView; Infomodel =NewInfomodelimpl (); }//For UI dispatching     Public void Saveinfo(Infobean Bean)    {Infomodel.setinfo (bean); }//For UI dispatching     Public void GetInfo() {//By calling the Iinfoview method to update the display, the design pattern uses        //Similar callback listener processingInfoview.setinfo (Infomodel.getinfo ()); }}

Looking back at the view layer code, the view layer also implements the abstract interface provided by the view layer (that is, the activity class, which acts as a UI View).

The implementation code for the view layer is shown below:

 Public  class mainactivity extends actionbaractivity  implements  Iinfoview, View. Onclicklistener {    PrivateEditText inputID, InputName, inputaddr;PrivateButton savebtn, loadbtn;PrivateTextView Infotxt;PrivatePresenter Presenter;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    InitData (); }Private void InitData() {presenter =NewPresenter ( This);        inputID = (EditText) Findviewbyid (r.id.id_input);        InputName = (EditText) Findviewbyid (r.id.name_input);        Inputaddr = (EditText) Findviewbyid (r.id.addr_input);        SAVEBTN = (Button) Findviewbyid (r.id.input_confirm);        LOADBTN = (Button) Findviewbyid (r.id.get_confirm);        Infotxt = (TextView) Findviewbyid (r.id.show); Savebtn.setonclicklistener ( This); Loadbtn.setonclicklistener ( This); }@Override     Public void SetInfo(Infobean info) {StringBuilder Builder =NewStringBuilder ("");        Builder.append (Info.getid ()); Builder.append ("\ n");        Builder.append (Info.getname ()); Builder.append ("\ n");        Builder.append (Info.getaddress ());    Infotxt.settext (Builder.tostring ()); }@Override     PublicInfobeanGetInfo() {Infobean info =NewInfobean ();        Info.setid (Integer.parseint (Inputid.gettext (). toString ()));        Info.setname (Inputname.gettext (). toString ()); Info.setaddress (Inputaddr.gettext (). toString ());returnInfo }@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.input_confirm:presenter.saveinfo (GetInfo ()); Break; CaseR.id.get_confirm:presenter.getinfo (); Break; }    }}

To this decoupled parallel development of the app coding work has been completed, the following shows the results of the operation:

Full engineering code point I go to the download page

Summary

The above example shows that the View (Activity) is only responsible for handling the user interaction, and the data-related logical operations are given to presenter to do, and presenter call model after processing the data, The view display information is updated through the view's abstract interface. This enables a complete decoupling of the UI and logical operations.

However, this view is also standing in the context of the app's local code to look at, for small apps completely unnecessary, large-scale apps and interactive complex can consider such processing, can be decoupled, but also easy to write test testing code.

On the development of Android application layer with MVP

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.