The concept, application and difference of Android MVC, MVP, and MVVP

Source: Internet
Author: User

Young man does not know the taste of sorrow, love the upper floor. Love the upper floor, to give new words strong say sorrow.

Now I know the taste of sorrow. Want to say also Hugh, but road days cool good autumn.

A Xin Ji-ji's "ugly slave" book Bo Shan Road in the middle wall "to everyone

Overview

MVC, MVP, and MVVM are all patterns that arise in order to resolve interface rendering and logical code separation. The classic MVC pattern is the ancestor of the M-v-x model, with both MVP and MVVM evolving on the basis of MVC. This article is divided into three parts:

    1. Outlines the concepts, differences, and scenarios for MVC, MVP, and MVVM.
    2. Use demo to demonstrate MVP and MVVM usage
    3. Demo Source Download
Outlines the concepts, differences, and scenarios for MVC, MVP, and MVVM. Brief Introduction to MVC

    • M-model: Business logic and entity model (Biz/bean)
    • V-view: Layout file (XML)
    • C-controllor: Controller (Activity)

Although MVC separates the interface rendering from the logic code, it does not really play a role in actual Android development. The XML file that the view corresponds to can actually do very little, a lot of interface shows by the controllor corresponding activity to do, so that the activity becomes a similar between the view and the controllor thing. If it's a small project, there's no problem with MVC. Because the project is relatively small, the development cycle is short, controllor bloated point can also be understood. Assuming the project more and more, especially with more complex logic, this time an activity thousands of lines of code compared to the egg pain, add a bit of the indentation, that acid cool ~ tut. So MVC is more suitable for small projects that are developed quickly.

Brief description of MVP

    • M-model: Business logic and entity model (Biz/bean)
    • V-view: Layout file (XML) and activity
    • P-presenter: Completing the interaction of the view and model

Although the MVC design is very nice, but the problem of code bloat is still not well resolved, this time the MVP will be on the scene. You can see that the MVP changes are very large relative to the MVC. Activity is used directly as a view instead of P-presenter in MVC C. Comparing the model diagram of MVC and MVP, we can find that the biggest change is that the view and model are not communicating directly, and all the interaction work is solved by presenter. Since both are communicated through presenter, for reuse and extensibility, the MVP model is well understood based on the interface design. Both are communicated through presenter, with many benefits, such as improved code reusability, increased extensibility, reduced coupling, and clearer code logic. However, the two things that can communicate directly now to communicate through a third party, it is bound to add a lot of classes. Yes, the MVP model is good, but it adds a lot of interfaces and implementation classes. The code logic is clear, but the code is much larger. When just take over a rotten tail of the MVP model, if you do not know the MVP, will be a face of the ignorant. So MVP is more suitable for small and medium-sized projects, large projects with caution.

Brief introduction to MVVM

    • M-model: Solid Model (Biz/bean)
    • V-view: Layout file (XML)
    • Vm-viewmodel:binder where a public property, view and model bindings are exposed

Some readers should say that you are acting like MVC! Yes, the corresponding file looks exactly the same, but it works differently. Like MVVM and MVP, view and model do not allow direct interaction. Only through ViewModel. The magical thing about MVVM is that the UI layer and the business logic layer are isolated through viewmodel, reducing the coupling of the program. Furthermore, the layout file can be used for view logic! And the model changes, and the view changes as well. Layout file can actually write logic, dismissed one!

Demo Demo MVP and MVVM code example using MVP

The project outline is as follows:

Preview the outline to find only one bean:user. Business logic has only one getuserinfo. Drop the view layer and the presenter layer first. Let's look at the simplest bean layer and the Biz layer (business logic).

public class User {private int id;    Private String account;    Private String pwd; Getter ()/setter () ...} public interface Igetuserinfo {void getuserinfo (int id, Onuserinfolistener listener);} public class Getuserinfoimpl implements igetuserinfo{@Override public void GetUserInfo (final int ID, final Onuserin  Folistener listener) {//Analog data New Thread (new Runnable () {@Override public void run ()                    {if (id = = 666) {User user = new User ();                    User.setid (666);                    User.setaccount ("A mouthful of three buns");                    User.setpwd ("Walking on the Road of Courage");                listener.getuserinfosuccess (user); }else{String msg = "Damage color!"                    Failed to get data ";                Listener.getuserinfofailure (msg);    }}). Start ();    }}public interface Onuserinfolistener {void getuserinfosuccess (user user); void Getuserinfofailure (String msg);}

In order to ornamental, omitted part of the code, if necessary, can be downloaded in the third part of the source. Here we define two interfaces and implementation classes. The MVP mode interface is much more visible. The following one by one explains the role of each class

    • User:bean can also be called Pojo, the Pure class.
    • Igetuserinfo: interface to get user information
    • Getuserinfoimpl: Get the implementation class for user information
    • Onuserinfolistener: The listener interface for obtaining user information

Here we mainly parse the Getuserinfoimpl class, Getuserinfoimpl is the specific implementation class of interface Igetuserinfo. The Igetuserinfo#getuserinfo () method is replicated. In Getuserinfoimpl's GetUserInfo () method, the background request data is simulated. If the user information is successfully requested, the interface OnUserInfoListener#getUserInfoSuccess(User user) method is called. Otherwise, the method is called OnUserInfoListener#getUserInfoFailure(String msg) .

The business logic for both the bean and the biz layer is available, and the following is the notification view displaying the data. Because the view model uses interface communication in presenter, first define an interface for displaying the data. This interface is then implemented in the activity where the data is to be obtained, and all of the abstract methods are replicated.

 public interface IUserInfoShow {    void beforeLoding();    void getUserInfoSucceed(User user);    void getUserInfoFailed(String msg);    

After the interface definition of the

View layer is complete, the last big Boss-presenter is left!

Package com.dyk.mvp.presenter; Import Com.dyk.mvp.bean.user;import Com.dyk.mvp.biz.igetuserinfo;import Com.dyk.mvp.biz.onuserinfolistener;import com.dyk.mvp.view.iuserinfoshow;/** * Created by DYK on 2016/4/14.    */public class Userinfopresenter {private Igetuserinfo migetuserinfo;    Private Iuserinfoshow muserinfoshow; Public Userinfopresenter (Iuserinfoshow muserinfoshow, Igetuserinfo migetuserinfo) {this.muserinfoshow = MUserInfoS        how;    This.migetuserinfo = Migetuserinfo;        } public void GetUserInfo (int id) {muserinfoshow.beforeloding (); Migetuserinfo.getuserinfo (ID, new Onuserinfolistener () {@Override public void getuserinfosuccess (Us                ER user) {muserinfoshow.getuserinfosucceed (user);            Muserinfoshow.afterloading (); } @Override public void Getuserinfofailure (String msg) {Muserinfoshow.getuserinfofai                LED (msg); Muserinfoshow.afterloading ();    }        }); }}

In the critical presenter, we define a two-parameter construction method and a GetUserInfo () method.

In the construction method, the two parameters passed in are: Iuserinfoshow, Igetuserinfo. The former is the top-level interface of the view layer, which is the top interface of the M layer. and assign to attribute Muserinfoshow, Migetuserinfo. It seems that all the work today looks at both of them!

In the GetUserInfo () method, the ID of the parameter passed in, which is the ID of the user. At the beginning of the method invocation mUserInfoShow.beforeLoding() , which means that we can do some preprocessing in the implementation of the Iuserinfoshow class Beforeloding () method, such as displaying loading animation and so on, followed by the call mIGetUserInfo.getUserInfo() , And new has an anonymous inner class of Onuserinfolistener. That is, we have access to user information monitoring. The next step is simple, and if successful then the call and mUserInfoShow.getUserInfoSucceed(user); mUserInfoShow.afterLoading(); the failed mUserInfoShow.getUserInfoFailed(msg); call mUserInfoShow.afterLoading(); . A simple presenter is done, the rest depends on the Iuserinfoshow implementation class

Package Com.dyk.mvp;import Android.app.activity;import Android.os.bundle;import android.util.log;import Com.dyk.mvp.bean.user;import Com.dyk.mvp.biz.getuserinfoimpl;import Com.dyk.mvp.presenter.UserInfoPresenter; Import Com.dyk.mvp.view.iuserinfoshow;public class Mainactivity extends Activity implements Iuserinfoshow {private STA    Tic final String TAG = "MVP";    Private Userinfopresenter Muserinfopresenter;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Muserinfopresenter = new Userinfopresenter (This, new Getuserinfoimpl ());    Muserinfopresenter.getuserinfo (666);    } @Override public void beforeloding () {log.i (TAG, "beforeloding"); } @Override public void getuserinfosucceed (user user) {log.i (TAG, "ID:" +user.getid () + "account:" +user.getacc    Ount () + "pwd:" +user.getpwd ()); } @Override public void getuserinfofailed (String msg){LOG.I (TAG, "msg=" + msg);    } @Override public void afterloading () {log.i (TAG, "afterloading"); }}

In Mainactivity#oncreate (), a Userinfopresenter object is instantiated first, and Getuserinfoimpl is passed in as a second parameter. Then just execute one line of code mUserInfoPresenter.getUserInfo(666); . The activity's code does not look much more concise. The log information is as follows:

MVVM code sample

The project outline is as follows:

wtf! Only activity, beans, and a activity_main.xml? Yes, MVVP is so concise. But brevity does not mean simplicity. Google last year I/O conference released a MVVP framework, data binding. Today, take this framework as an example.
Add in module's Build.gradle

dataBinding {    enabled true}

The code is very small and is directly attached. It will be explained carefully later.

<?xml version= "1.0" encoding= "Utf-8"? ><layout xmlns:android= "Http://schemas.android.com/apk/res/android"            > <data> <import type= "Com.dyk.mvvp.bean.User"/> <variable name= "User" Type= "User"/> </data> <linearlayout android:layout_width= "Match_parent" Android:la yout_height= "match_parent" android:orientation= "vertical" > <textview android:layout_width= "        Match_parent "android:layout_height=" wrap_content "android:text=" @{string.valueof (user.id)} "/>            <textview android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "@{user.account}"/> <textview android:layout_width= "Match_parent" Android  oid:layout_height= "Wrap_content" android:text= "@{user.pwd}"/> </linearlayout></layout>public Class Mainactivity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        activitymainbinding binding = Databindingutil.setcontentview (this, r.layout.activity_main);    Binding.setuser (New User (666, "a mouthful of three buns", "walking on the Road of Courage")); }}

Run for a try. Just a few lines of code. The binding and presentation of user information first look at the layout file. The outermost layer is layout. The data element is then defined with a variable (variable) named user, the com.dyk.mvvp.bean.User user in the type, and our bean. TextView.setText()you can then use the User.account property directly in to get the properties of the user, whether private or not. Java primitives do not use the Import guide package, and Java syntax is also supported. You can see that the id attribute String.value() is converted to string using the method. Then the mainactivity is not directly setContentView() called but the DataBindingUtil.setContentView(this, R.layout.activity_main); return is an inherited ViewDataBinding generic. Here it is ActivityMainBinding , note that this return generic name is regular: The layout file goes off the dash, the first letter is capitalized, and the binding is appended. For example, here the layout file is activity_main , the corresponding generic is: ActivityMainBinding , here is just an example. Interested students can study the data binding framework carefully.

SOURCE Download: http://download.csdn.net/detail/qq_17250009/9492043

Reference:

http://blog.csdn.net/loongggdroid/article/details/50592777
http://blog.csdn.net/lmj623565791/article/details/46596109
http://rocko.xyz/2015/02/06/Android%E4%B8%AD%E7%9A%84MVP/
Http://rocko.xyz/2015/11/07/MVVM_Android-CleanArchitecture/
http://blog.csdn.net/johnny901114/article/details/50706329
http://blog.csdn.net/qibin0506/article/details/47393725
Http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/1110/3669.html

The concept, application and difference of Android MVC, MVP, and MVVP

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.