On the MVC and MVP model in Android

Source: Internet
Author: User

Using MVC or MVP mode will add a lot of classes, but it can make the code structure clear, convenient for later maintenance and expansion. Separating the data layer from the view layer, the logic for handling the transaction is placed in a single class, allowing the activity to have only the display function.

Here we explain the MVC pattern and the MVP model separately, in short, there are pros and cons. In the actual development, we choose according to the actual situation. Personally, the MVP model is a bit simpler because the MVP model will take part of the logic activity, but this causes the activity to be relatively cumbersome, not to achieve complete isolation. The MVC pattern we are using is a better way to deal with this problem, but in the process of application, some logic may be more around.

Let's take a user login example to understand the two patterns separately.

Let's start by explaining the MVC pattern:

It is said here that the MVC pattern is not the traditional MVC pattern, thanks to the Aurora Push IM provides demo, this demo is an MVC model, the concrete implementation of the idea is to model layer, view layer, controller layer separation, The activity is only used to load the view use, the initialization control to the view layer, the data to the model layer, the processing of data to the controller layer, our activity is unusually refreshing!

let's start by designing the view layer, customizing a view, inheriting from the viewgroup we need, LinearLayout or Framelayout and so on. The purpose of our customizations is to instantiate the control in the next step so that it does not have to be instantiated in the activity. Here we simply inherit, usually do not need to own more logic, so do not panic. The code is as follows:

public class LoginView extends relativelayout{    private Context mcontext;    /**     * Because we are using it in the layout file, we just need to rewrite this constructor method     * @param context     * @param attrs *     /public    LoginView ( Context context, AttributeSet Attrs) {        Super (context, attrs);        This.mcontext = context;    }}


Now we're going to use the already definedViewGroup to layout, just a simple login window, a username, a password, and a login button:

<?xml version= "1.0" encoding= "Utf-8"? ><com.baiyyyhjl.mode.mvc.view.loginview xmlns:android= "/http Schemas.android.com/apk/res/android "android:layout_width=" match_parent "android:layout_height=" Match_parent " > <edittext android:id= "@+id/et_username" android:layout_width= "Match_parent" android:layout _height= "wrap_content" android:hint= "User name" android:padding= "10DP"/> <edittext android:id= "@+ Id/et_password "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Android:layo ut_below= "@id/et_username" android:hint= "password" android:padding= "10DP"/> <button android:id= "@ +id/btn_login "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layou t_below= "@id/et_password" android:padding= "10DP" android:text= "Login"/></com.baiyyyhjl.mode.mvc.view.log Inview>


Now we add the method of initialization of the control in LoginView.

public void Initmodule () {        musername = (EditText) Findviewbyid (r.id.et_username);        Mpassword = (EditText) Findviewbyid (R.id.et_password);        MLOGINBTN = (Button) Findviewbyid (r.id.btn_login);    }


Get to the content in EditText and listen to MLOGINBTN Click events, here we can add more information about the view, all according to the actual needs to:

    Public String GetUserName () {        return Musername.gettext (). toString (). Trim ();    Public String GetPassword () {        return Mpassword.gettext (). toString (). Trim ();    public void Setlisteners (Onclicklistener onclicklistener) {        mloginbtn.setonclicklistener (onclicklistener);    }    public void Usernameerror (context context) {        Toast.maketext (context, "User name cannot be empty", Toast.length_short). Show ();    Public    void Passworderror (context context) {        Toast.maketext (context, "Password cannot be empty", Toast.length_short). Show () ;    }    public void loginsuccess (context context) {        Toast.maketext (context), "Login succeeded!" ", Toast.length_short). Show ();    }    public void Loginfailure (context context) {        Toast.maketext (context), "Login failed. ", Toast.length_short). Show ();    }}


Well, a view layer has been completed, the following is the model layer, mainly on the data request, such as the acquisition of data in the database, network requests, etc.:

Here we assume that the network request, a Loginmodel, has a callback interface to return the results, the specific simulation code is as follows:

<pre style= "font-family: Song body; font-size:15pt; Background-color:rgb (255, 255, 255); " ><pre name= "code" class= "Java" >public class Loginmodel implements Iloginmodel {@Override public void login (Final string username, final string password, final resultcallback callBack)    {//Simulate the time-consuming operation of a sub-thread, such as a network request, where we use asynchronous request new Myasynctask (CallBack). Execute (username, password);        } private class Myasynctask extends Asynctask<string, Void, boolean>{resultcallback mcallback;        Public Myasynctask (Resultcallback callBack) {this.mcallback = CallBack; } @Override protected Boolean doinbackground (String ... params) {try {Thread.slee            P (2000);            } catch (Interruptedexception e) {e.printstacktrace ();            } if (Params[0].equals ("Hjl") && params[1].equals ("123456") {return true;            } else {return false;    }    } @Override protected void OnPostExecute (Boolean aboolean) {if (Aboolean) {MC            Allback.success ();            } else {mcallback.failure (); }        }    }}


Finally implement the controller layer:

public class Logincontroller implements view.onclicklistener{private LoginView Mloginview;    Private Mvcloginactivity Mcontext;    Private Iloginmodel Mloginmodel;        Public Logincontroller (LoginView LoginView, mvcloginactivity context) {This.mloginview = LoginView;        This.mcontext = context;    Mloginmodel = new Loginmodel ();                } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_login:                Final String username = Mloginview.getusername ();                Final String password = Mloginview.getpassword ();                    if (Textutils.isempty (username)) {mloginview.usernameerror (mcontext);                Break                    } if (Textutils.isempty (password)) {mloginview.passworderror (mcontext);                Break        }//Call the model layer for network request Mloginmodel.login (username, password, new Resultcallback () {            @Override public void Success () {mloginview.loginsuccess (mcontext);                    Mcontext.finish (); } @Override public void failure () {mloginview.loginfailure (M                    Context);                }                });        Break }    }}

So the MVC framework is done and shown in the activity:

public class Mvcloginactivity extends Appcompatactivity {    private LoginView Mloginview = null;    Private Logincontroller Mlogincontroller;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.mvc_activity_login);        The binding of the control        Mloginview = (LoginView) Findviewbyid (R.id.login_view);        Mloginview.initmodule ();        Mlogincontroller = new Logincontroller (Mloginview, this);        Event Listener        mloginview.setlisteners (Mlogincontroller);}    }

A relatively complex login operation, in our activity only a few simple lines of code, the specific logic is all given to MVC, where our idea is that activity is not part of the view layer, but only for the display and some simple logic processing, we put the MVC layer all alone into several classes, Let the activity in just a few lines of code, and the overall code structure is quite clear! Summary: For the control of the binding and other related operational logic we write in the view layer, for the data acquisition (read the database, get network data) We write in the model, for the code of all the logic (click event Processing, related events) and so we write in the controller layer.

Next we introduce the MVP model, the personal feeling that this model better understand, the drawbacks at the beginning of the article has been said.

Before I saw the Great God analyzed MVP mode, in fact my first contact with this mode is I just work soon, the company project. At that time because the foundation is not good, always feel super trouble, is so many classes, so many interfaces, directly written in the activity more convenient. Later the code to write a little more, found that if all writing in the activity is very difficult to maintain, and sometimes more code, may not be able to read their own code to write, but also gradually understand the benefits of design patterns.


Let's take this login requirement as an example, and use the MVP mode to write it over and experience it. Model layer is also the entity model and business logic, the view layer here we directly use activity, that is, bound controls and other operations in the activity, no longer a class, the presenter layer is responsible for processing the model and the interaction between the view.

The first is to write the view layer interface Iloginview, where we need to take all the necessary conditions into account:

Public interface Iloginview {    String getusername ();    String GetPassword ();    void Usererror (context context);    void Passworderror (context context);    void Loginsuccess (context context);    void Loginfailure (context context);


Next is the model layer, which simulates the network request

public class Loginmodel implements Iloginmodel {    @Override public    void Login (final string username, final string p Assword, Final Resultcallback callBack) {        new Thread (new Runnable () {            @Override public            void Run () {                try {                    Thread.Sleep (+);                } catch (Interruptedexception e) {                    e.printstacktrace ();                }                if (Username.equals ("Hjl") && password.equals ("123456")) {                    callback.success ();                } else {                    Callback.failure ();}}        ). Start ();    }}


Finally implemented in activity:

public class Mvploginactivity extends Appcompatactivity implements View.onclicklistener, Iloginview {private EditText    Musername;    Private EditText Mpassword;    Private Button mloginbtn;    Private Loginpresenter Mloginpresenter;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.mvc_activity_login);        Mloginpresenter = new Loginpresenter (this);    Initview ();        } private void Initview () {musername = (EditText) Findviewbyid (r.id.et_username);        Mpassword = (EditText) Findviewbyid (R.id.et_password);        MLOGINBTN = (Button) Findviewbyid (R.id.btn_login);    Mloginbtn.setonclicklistener (this);    @Override public String GetUserName () {return Musername.gettext (). toString (). Trim ();    @Override public String GetPassword () {return Mpassword.gettext (). toString (). Trim (); } @Override public void Loginsuccess () {Toast.Maketext (This, "Login successful", Toast.length_short). Show ();    Finish ();    } @Override public void Loginfailure () {Toast.maketext (this, "User name or password error", Toast.length_short). Show ();                } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_login:                    if (Textutils.isempty (GetUserName ())) {Toast.maketext (this, "User name cannot be empty", Toast.length_short). Show ();                Break } if (Textutils.isempty (GetPassword ())) {Toast.maketext (this, "Password cannot be empty", toast.length_sh                    ORT). Show ();                Break                } mloginpresenter.login ();        Break }    }}


The above is the two design patterns in Android, do not know whether they write standards, but feel that this has reached the code structure of the clear. One of the MVC is to learn from the Aurora push IM demo, and feel that the way he writes this method is great. The second is used in the project, but also very simple and clear.

The above mentioned demo download click the Open link





On the MVC and MVP model in Android

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.