Introduction to MVP Android Application Layer Development and mvpandroid

Source: Internet
Author: User

Introduction to MVP Android Application Layer Development and mvpandroid

Finally, CSDN was chosen to sort out the knowledge points published over the past few years. This article was migrated to CSDN in parallel. Because CSDN also supports the MarkDown syntax, it's awesome!

[Craftsman's water: http://blog.csdn.net/yanbober]

Background

The reason for this is that when you develop an App, you may find that Activity is very responsible. If you look at your own developed App from the perspective of the MVC framework, generally, the setContentView of an xml layout file Activity acts as the View, other code of the Activity acts as the Controller, and other data sources (databases, etc.) Act as the Model. Therefore, you will find that the Activity violates the single responsibility principle and is overloaded. At the same time, if you want to test the logical data layer, you will find it difficult to write test cases. Is there a decoupling method?

Yes, that is, the MVP framework.

MVP Architecture

MVP is Model-View-Presenter. In fact, you don't need to explain much, as shown in:

As shown in, the MVP mode must have the following three elements:

The tangle of programmers-MVP and MVC

After reading the above two paragraphs, you may wonder about the MVP. What is the relationship between them?

Let's take a look at MVC!

MVC Architecture

The MVC framework considers that the software can be divided into the following three parts:

  • View: user interface.
  • Controller: business logic.
  • Model: save data.

For example, the core of the MVC framework is intuitively displayed:

View sends commands to the Controller. After the Controller completes the business logic, the Model is required to change the status. The Model sends new data to the View and the user receives feedback.

Comparison between MVP and MVC

At this time, you will find that the structure of MVC and MVP are very different, the specific differences are as follows:

MVP architecture:

The View does not directly interact with the Model, but indirectly interacts with the Model by interacting with the Presenter.
Presenter interacts with View through interfaces.
Generally, a View and a Presenter are one-to-one, but a complex View may be bound to multiple presenters to process logic.

MVC Architecture:

View can directly interact with the Model.
The Controller is behavior-based and can be shared by multiple views.
You can decide which View to display.

Summary

MVC is very similar to MVP, but there is a big difference. There are different points of view from different analysis perspectives. Here we only analyze the results based on the Android App code.

Android applications of MVP architecture:

Complete project code click I enter the download page

Background:The following example simulates a user interaction to access data. After the user inputs the data, click Save. Then, click get data to obtain the data to be saved.
UI:

Project directory structure:

Code details:

First, let's take a look at the model-Layer Code. The model layer provides abstract interfaces to facilitate decoupling and facilitate impl implementation code of the test case test model. The following shows the abstract interface and implementation code.

Model layer abstract interface:

Public interface IInfoModel {// method for obtaining data from the data provider InfoBean getInfo (); // Method for storing data provider void setInfo (InfoBean info );}

Model layer abstract implementation:

Public class InfoModelImpl implements IInfoModel {// simulate storage data private InfoBean infoBean = new InfoBean (); @ Override public InfoBean getInfo () {// simulate storage data, actually there are many operations: return infoBean;} @ Override public void setInfo (InfoBean info) {// simulate data storage. There are actually many operations: infoBean = info ;}}

Next, let's look at the View-Layer Code. The View-layer also provides abstract interfaces to facilitate decoupling and to facilitate the impl of the test case test View to implement interactive code. The following shows the abstract interface code.

Abstract interface of View layer:

Public interface IInfoView {// Method for displaying data to the UI void setInfo (InfoBean info); // Method for retrieving data from the UI InfoBean getInfo ();}

In this case, you can think about the division of labor between users who write the UI and logic. They can connect to each other through interfaces. The Presenter role is more like an adapter class in design mode, which is responsible for interfacing with the UI and data logic. So let's take a look at the implementation of Presenter:

Public class Presenter {private IInfoModel infoModel; private IInfoView infoView; public Presenter (IInfoView infoView) {this. infoView = infoView; infoModel = new InfoModelImpl ();} // provide public void saveInfo (InfoBean bean) {infoModel. setInfo (bean);} // call the IInfoView method to update and display public void getInfo () {// use the callback listener in the design mode to process infoView. setInfo (infoModel. getInfo ());}}

At this time, let's look back at the View-Layer Code. The View-layer also implements the abstract interface provided by the View-layer (that is, the Activity class, acting as the UI View ).

The implementation code of the View layer is as follows:

public class MainActivity extends ActionBarActivity implements IInfoView, View.OnClickListener{    private EditText inputId, inputName, inputAddr;    private Button saveBtn, loadBtn;    private TextView infoTxt;    private Presenter presenter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initData();    }    private void initData() {        presenter = new Presenter(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 = new StringBuilder("");        builder.append(info.getId());        builder.append("\n");        builder.append(info.getName());        builder.append("\n");        builder.append(info.getAddress());        infoTxt.setText(builder.toString());    }    @Override    public InfoBean getInfo() {        InfoBean info = new InfoBean();        info.setId(Integer.parseInt(inputId.getText().toString()));        info.setName(inputName.getText().toString());        info.setAddress(inputAddr.getText().toString());        return info;    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.input_confirm:                presenter.saveInfo(getInfo());                break;            case R.id.get_confirm:                presenter.getInfo();                break;        }    }}

By now, the App code for decoupling parallel development has been completed, and the running results are shown as follows:

Complete project code click I enter the download page

Summary

Through the above example, we can find that View (Activity) is only responsible for processing user interaction, and all data-related logical operations are handed over to the Presenter. After Presenter calls the Model to process data, then, update the information displayed by the View through the abstract interface of the View. In this way, the UI and logic operations are fully decoupled.

However, this point of view is also viewed from the perspective of partial App Code. It is not necessary for small apps. Large apps and complex interactions can be considered for such processing, which can be decoupled, you can also easily write test code.

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.