The application of MVP model in Android development _android

Source: Internet
Author: User

First, the MVP introduction

As the functionality of the UI creation technology grows, the UI layer also performs more and more responsibilities. In order to better subdivide view and model function, let view focus on processing data visualization and interaction with the user, while let the model only relational data processing, based on the MVC concept of the MVP (Model-view-presenter) model emerged.

The MVP model usually contains 4 elements:

(1) View: Responsible for drawing UI elements, interacting with users (represented as activity in Android);

(2) View interface: Need view implementation of the interface, view through the view interface and presenter interaction, reduce coupling, facilitate unit testing;

(3) Model: Responsible for storing, retrieving, manipulating data (sometimes also implement a model interface used to reduce coupling);

(4) Presenter: As an intermediate link between view and model, handling the responsible logic of interacting with the user.

Second, why use the MVP model

In Android development, activity is not the controller of a standard MVC pattern, and its primary responsibility is to load the applied layout and initialize the user interface, and accept and process requests from users to respond. As the complexity of the interface and its logic continues to rise, the responsibilities of the activity class increase and become bloated. When we move a complex logical process into another class (Presneter), the activity is actually the view in the MVP mode, which is responsible for the initialization of UI elements, the association of UI elements with presenter (listener, and so on), At the same time, they also handle some simple logic (complex logic referred to presenter processing).

Also, think back to how you tested the code logic when you were developing Android apps? Do you want to deploy the application to the Android emulator or the real machine every time, and then test it by simulating user actions? However, because of the characteristics of the Android platform, each deployment consumes a lot of time, which directly leads to the reduction of development efficiency. And in MVP mode, the presenter that handles complex logic is interacting with the view (activity), what does that mean? interface This shows that we can implement this interface to simulate the behavior of the activity of the presenter Unit test, save a lot of time for deployment and testing.

The similarities and differences between MVP and MVC

Both the MVC pattern and the MVP model have been applied for many years as a development model for separating the UI layer from the business layer. When we choose a development model, we first need to understand the pros and cons of this model:

Either MVC or the MVP model inevitably has one drawback: additional code complexity and learning costs.

This leads to the two development patterns that may not be very small applications.

But compared to their advantages, this shortcoming can be ignored basically:

(1) Reduce the coupling degree

(2) Module Responsibility Division is obvious

(3) Conducive to test-driven development

(4) Code reuse

(5) Hide Data

(6) Code flexibility

There is also a big difference between the two modes of MVP and MVC. Some programmers choose not to use any of these patterns, partly because they may not be able to distinguish between the two patterns.

(Reference article: http://www.infragistics.com/community/blogs/todd_snyder/archive/2007/10/17/ mvc-or-mvp-pattern-whats-the-difference.aspx)

MVP mode:

    • 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 interfaces and is more conducive to adding unit tests
    • Usually view and presenter are one-to-one, but complex view may bind multiple presenter to handle logic

MVC pattern:

    • View can interact directly with model
    • Controller is based on behavior and can be shared by multiple view
    • is responsible for deciding which view to display

Iv. examples of using MVP for Android development

Having said so many theories, it's time to practice.

Now we're going to implement this Android demo (pictured): You can read user information from EditText and access it, or you can read the user information from the background and display it based on the ID.

The page layout is very simple, do not introduce. The following is encoded according to the MVP principle:

Let's look at the directory structure of the Java file:

It can be found that presenter and model, view are interactive through the interface, both reduce coupling and facilitate unit testing.

(1) First we need a Userbean to save the user information

public class UserBean { 
   private String mfirstname; 
   Private String mlastname; 
   Public UserBean (String firstName, String lastName) {This 
      mfirstname = firstName; 
      This mlastname = LastName; 
   } 
   Public String Getfirstname () {return 
      mfirstname; 
   } 
   Public String Getlastname () {return 
      mlastname; 
   

(2) Look at the View interface again:

Depending on the requirements, view can read the three edittext of IDs, FirstName, LastName, write to FirstName and LastName, thereby defining the Iuserview interface:

Public interface Iuserview { 
    int getID (); 
    String getfristname (); 
    String getlastname (); 
    void Setfirstname (String firstName); 
    void Setlastname (String lastName); 

(3) Model interface:

Similarly, model also needs to read and write to these three fields, and stored in a carrier (this is not our concern, can exist in memory, file, database or remote server, but for presenter and view has no effect), define the Iusermodel interface:

Public interface Iusermodel { 
    void SetID (int id); 
    void Setfirstname (String firstName); 
    void Setlastname (String lastName); 
    int GetID (); 
    UserBean load (int id);//Read the user information by ID, return a UserBean 

(4) Presenter:

At this point, presenter can interact with view and model through the interface:

public class Userpresenter { 
    private iuserview muserview; 
    Private Iusermodel Musermodel; 
 
    Public Userpresenter (Iuserview view) { 
       Muserview = view; 
       Musermodel = new Usermodel (); 
    } 
 
    public void Saveuser (int id, string firstName, String lastName) { 
       Musermodel SetID (ID); 
       Musermodel Setfirstname (firstName); 
       Musermodel Setlastname (lastName); 
    } 
 
    public void Loaduser (int id) { 
       UserBean user = Musermodel load (ID); 
       Muserrview setfirstname (User getfirstname ());//update display Muserview Setlastname () by calling Iuserview method (user 
       getlastname ()) ); 
    } 
} 

(5) Useractivity:

The useractivity implements the Iuserview and View.onclicklistener interfaces, along with a userpresenter member variable:

public class Useractivity extends activity implements Onclicklistener, 
       iuserview { 
 
    private edittext Mfirstnameedittext, Mlastnameedittext, Midedittext; 
    Private Button Msavebutton, Mloadbutton; 
    

Overridden the OnClick method:

@Override public 
    void OnClick (View v) { 
       //TODO auto-generated a stub 
       switch (v getId ()) {case 
       R ID Savebutton: 
          muserpresenter saveuser (GetID (), Getfristname (), 
                getlastname ()); 
          break; 
       Case R ID Loadbutton: 
          muserpresenter loaduser (GetID ()); 
          break; 
       Default: Break 
          ; 
       } 
    } 

As you can see, view is only responsible for dealing with the user to interact with, and the data related to the logical operations are thrown to the presenter to do. The presenter call model finishes processing the data, and then updates the information displayed by the view through Iuserview.

View the remaining methods and Usermodel class is not our focus, if you are interested can click on the link below to download.

The source code is here.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.