50 Android Development Tips (20 using MVP mode)

Source: Internet
Author: User

I. Introduction of the MVPAs UI creation technology becomes more and more powerful, the UI layer is performing more and more responsibilities.     In order to better subdivide the view and model functions, let view focus on processing data visualization and interaction with the user, while the model only relational data processing, based on the MVC concept of the MVP (Model-view-presenter) model emerged. In MVP mode, there are usually 4 elements: (1)View: Responsible for drawing UI elements, interacting with the user (embodied as activity in Android); (2)View Interface: Requires view implementation interface, view through the view interface and presenter interaction, reduce coupling, convenient for unit testing; (3)Model: Responsible for storing, retrieving, manipulating data (sometimes also implementing a model interface to reduce coupling); (4)Presenter: As an intermediate link between view and model, handles the responsible logic for interacting with the user. (Original address: http://blog.csdn.net/vector_yi/article/details/24719873)
Second, why use MVP modeIn Android development, activity is not a controller in the standard MVC pattern,its primary responsibility is to load the application's layout and initialize the user interface, and to accept and process the action requests from the user to respond. As the complexity of the interface and its logic increases, so does the responsibility of the activity class to become bloated. When we move the complex logic processing to another class (Presneter), the activity is actually a view in the MVP mode, which is responsible for initializing the UI elements, establishing the association of UI elements with presenter (listener, etc.). At the same time, I will handle some simple logic (complex logic to presenter processing).Also, recall how you unit-tested your code logic when you developed your Android app? Do you want to deploy your app to an Android emulator or a real computer every time, and then test it by simulating user actions? However, due to the features of the Android platform, each deployment takes a lot of time, which leads directly to the reduction of development efficiency. In MVP mode, the presenter that handles complex logic interacts with the view (Activity) through interface, what does that mean? It is explained that we can implement this interface by custom class to simulate activity behavior to unit Test presenter, save a lot of time for deployment and testing.
Iii. the similarities and differences between MVP and MVCBoth 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 look at the pros and cons of this model: no matter the MVC or MVP model inevitably has a disadvantage:Additional code complexity and learning costs. This leads to the two development patterns that may not be very small applications. But compared to their merits, this shortcoming basically can be neglected: (1) Reduce coupling degree (2) module Responsibility Division is obvious (3) conducive to test-driven Development (4) code reuse (5) Hidden Data (6) Code flexibility
There is also a big difference between the two models of MVP and MVC. There are some programmers who choose not to use any one of the patterns, and some of the reasons may be that they cannot differentiate between the two patterns. The following are the most critical differences between the two modes: (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 an interface, which is more conducive to adding unit tests
    • The view is usually one-to-presenter, but complex view may bind multiple presenter to handle the logic
MVC pattern:
    • View can interact directly with the model
    • The controller is behavior-based and can be shared by multiple view
    • Be responsible for deciding which view to display

Iv. Examples of using MVP for Android developmentHaving said so many theories, it is now the turn to practice. Now let's implement an Android demo (): You can read the 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 layout of the page is very simple and is not covered. The following is coded according to the MVP principle: First look at the directory structure of the Java file:
It can be found that presenter and model, view are interactive through the interface, both to 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: according to the requirements, the view can be the ID, FirstName, lastname the three EditText read operation, the FirstName and LastName write operations, 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, the model also needs to read and write the three fields, and stored in a vector (this is not our concern, can exist in memory, file, database or remote server, but for presenter and view no impact), 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 user information by ID, return a UserBean}
(4) Presenter:at this point, presenter can interact with the view and model via 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 the display Muserview. Setlastname by calling the Iuserview method             . User. Getlastname ());}       }
(5) Useractivity:Useractivity implements the Iuserview and View.onclicklistener interfaces with a userpresenter member variable:
public class Useractivity extends Activity implements Onclicklistener,             iuserview {       private EditText Mfirstnameedittext, Mlastnameedittext, Midedittext;       Private Button Msavebutton, Mloadbutton;       Private Userpresenter Muserpresenter;

overridden The OnClick method:
@Override public       void OnClick (View v) {             //TODO auto-generated Method 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 handling the interaction with the user and throwing the data-related logic operations to presenter. When presenter calls model to finish processing the data, the information displayed by the view is updated by Iuserview.
view the remaining methods and Usermodel class is not our concern, if interested can be viewed in the source code. The source is here.





50 Android Development Tips (20 using MVP mode)

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.