Thinking about the Android MVP model

Source: Internet
Author: User

Recently, I've seen a lot of blogs about MVP models, and I've written many Android apps, and it's always fast to do those apps, so you've been thinking about reuse from the start of the design to the writing code. Previously written projects are basically refactoring projects, streamlining project code, and improving the reusability of code. But the code does not specifically focus on the MVC pattern or the MVP model, but more directly consider modularity, reuse, and streamlining. So after watching the MVP model, I decided to summarize the problem in my code and optimize it, as a review of the code I wrote earlier.

MVP Framework

The MVP framework is currently popular in Android framework and it is well suited for Android development above. My first contact with the MVP model was in a book on agile development. MVP refers to M (model), V (View), P (Presenter), respectively:
-M (model): Represents the data model, and the associated data structure.
-V (view): Represents the view, mainly refers to the UI interface related to those things. In Android, such as the layout of XML files, in the MVP, many times Activity/fragment is also considered a view.
-P (Presenter): can be directly understood as the middle bond between the view and the model.

In MVP mode, model and view are not directly related, but are associated by presenter. Often the way to achieve is to add a Imodel interface and iview interface, with the model and the view to implement the two interfaces, presenter inside the Imodel and iview to save the interface type member variables.

code example

Here's an example of the MVP model for Android user information.

publicinterface IUserView{void setName(String name);}

User's Javabean-user:

class User{    private String name;    private String id;    publicgetName(){        return name;    }    publicgetId(){        return id;    }    publicvoidsetName(String name){        this.name = name;    }    publicvoidsetId(String id){        this.id = id;    }}

User Model interface

publicinterface IUserModel{void saveUser(User user);User load();}

Real model

publicclass UserModel implements IUserModel{    void saveUser(User user){        // 保存用户信息,保存在本地数据库中,或者xml里面    }    User loadUser(){        // 从网络中,或者从本地缓存中读取用户信息        returnnull//未实现    }}

Presenter:

publicclass UserPresenter{    private IUserView view;    private IUserModel userModel;    publicUserPresenter(IUserView view){        this.view = view;        new UserModel();    }    publicvoidloadUser(){        // 此处可能是异步load        User user = userModel.loadUser();        view.setName(user.getName());    }}

To see activity as a view

 Public  class useractivity extends Activity implements Iuserview{ TextView Tvname;//name corresponding to the TextViewUserpresenter Userpresenter; Public void onCreate(Bundle bundle) {... userpresenter =NewUserpresenter ( This);//Userpresenter.loaduser (); can be initialized first}voidSetName (String name) {tvname.settext (name);//If presenter's Loaduser is an asynchronous thread, it can be run through Tvname.post in the UI thread. }voidReloaduserdata () {//This function can be called in the OnClick event of a buttonUserpresenter.loaduser ();//May be to load data from the network}}

The activity in the above code is no longer directly associated with the model, but is indirectly associated with the model through presenter. And when the model data changes, presenter can notify the view. The example above is that the view needs to change and request presenter to get the data.

Analysis

The biggest difference between MVP and MVC is that view and model are no longer directly related. Many of the MVC patterns in Android are directly looking at activity as control, which can cause the whole activity to be bloated because it needs to add the functionality of the control section since it interacts with the UI. In addition, even if you create a new control, and the activity only as a function of the view, if the activity is directly related to the model, because it is directly related to the model, it will add a lot of operations in the activity. Instead of using p as the link between model and view, p can do some processing of the models ' data before displaying them to view. On the other hand for some of the view requests, presenter can also do some processing to request model.

The above is about the advantages of code, in fact, by separating the model and view, but also the various modules to understand the decoupling. On the other hand, by adding iuserview and Iusermodel, it is more convenient to unit test each part, such as can be directly implemented Iuserview to simulate the test presenter.

Personally, the MVP model is suitable for Android applications, a big reason is that the presence of this component of the activity, UI interaction is completely in the activity, which leads to a lot of time the activity will become bloated in a unnoticed. View is too large. There are, of course, many Android-related advantages, such as being able to better avoid memory leaks from activity (presenter directly referencing view, not activity). In fact, by increasing the presenter, to a certain extent also increased the presenter reuse, many people say that the view and presenter is one by one corresponding, but I think if not one after another, for example, an activity contains multiple presenter, The presenter refinement, so that the likelihood of presenter reuse is higher, but also to avoid the presenter too bloated.

A pattern optimization process

When you write your own code, it is actually less obvious to use this MVP mode, or the MVC pattern. More modularity, class hierarchies (object-oriented), aspect-oriented, and adherence to the principles of code simplification and reuse. Here's a simplified model of the usual project, and the process of turning the pattern into an MVP by considering optimizing the structure. Let's look at the following type of structure:

Firstly, modularization divides the program into fragment/activity part, adapter part, model network operation part, reduces the bloated class by layering related classes, and extracts some content from the child parent class by AOP programming, as a separate slice. This aspect-oriented can improve the reusability of code.

There is also an unreasonable example of the above type diagram, as described in the above note, the network operation as part of the model, rather than adding an interface, will cause the network operation once modified, will affect the model subclass.

Here's a look at how to convert the above structure. The above structure is more of an MVC approach, and it's basically a combination of V and C, which together can be more UI interactive, but can also lead to bloat. The above figure shows that only basefragment one-way to the model, which will inevitably lead to fragment add more code to control, because the Internet connection in Android is bound to operate in a non-UI thread, if the model is not connected to fragment, It is necessary to put an asynchronous operation into fragment, waiting for the model operation to complete, fragment to update the contents of fragment. If you add an interface and then fragment the implementation, and reference it with model, you will be able to reduce the fragment operation and be better able to unit test the model. If you add a presenter that is associated with fragment by presenter and then presenter is also associated with the model, then fragment will be much simpler and more focused on other UI interactions. Adding presenter the entire architecture becomes the MVP model. The reconstructed type diagram is as follows:

Summarize

Patterns always adhere to the reuse, low-coupling between modules, high cohesion within the module, and so on, there are six principles in the design pattern: Single duty principle, open and close principle, dependence reversal principle, Dimitri rule, Richter replacement principle, combined aggregation principle. A good pattern allows people to understand the code well when they are reading it, to be quick and concise when modifying a program, and not to destroy the original code structure.

Thinking about the Android MVP model

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.