A brief talk on the Android design mode MVP

Source: Internet
Author: User
Tags gettext

I. Overview

MVP (Model-view-presenter) is an evolution of the general known MVC model, whose main purpose is to divide module responsibilities, reduce module coupling, easily test, and improve code reuse, which is primarily for the Android platform to analyze the MVP.


1. Level of responsibility

Model: Responsible for data retrieval, persistence and other operations

View: Responsible for drawing the UI and interacting with the user

Presenter: As the intermediate coordination part of model and view, responsible for the business logic between the two


2. Differences from the MVC pattern

One of the main differences between the MVP mode and the MVC pattern is that the MVC pattern allows the view layer to communicate directly with the model layer. You can see the difference between MVP and MVC from Figure 1 and Figure 2.

In Figure 1MVC mode, the model can update data directly to the view layer. So when the functionality of a view is complex, the coupling of the view and model can be very high (and in the development of Android, activity usually acts as a controller&view role, The activity is very bloated). And the MVP model does not have this question, the view will abstract out a series of UI interface (the model layer can also), presenter got the other two levels of Interface to do business logic processing. This not only reduces the coupling between the view and the model, but also makes unit testing easier.


Figure 1:mvc Mode


Figure 2:MVP Mode


Advantages and disadvantages of 3.MVP

Pros: Reduced coupling, more obvious levels of responsibility, and easy unit testing

Cons: Explosion of class numbers, code complexity and high learning costs, and in some scenarios the reuse of presenter will produce interface redundancy



two. Simple examples of MVPusing MVP to write a simple login function, the homepage has two buttons: Login and Clear

1. Project structure



2.Model Layer

Contains an entity Userbean used to host data and userbiz to judge the login data

public class UserBean {    private String username;    private String password;    Public String GetUserName () {        return username;    }    public void Setusername (String username) {        this.username = username;    }    Public String GetPassword () {        return password;    }    public void SetPassword (String password) {        this.password = password;    }}


Userbiz by abstracting out an interface


Public interface Userbiz {public    void login (UserBean login);}

Userbizimpl instantiate the interface and callback the result to presenter by logging on to the listener

public class Usrbizimpl implements userbiz{    private Onloginlistener listener;    Public Usrbizimpl (Onloginlistener listener) {        This.listener = listener;    }    @Override public    void Login (UserBean login) {        Boolean status = FALSE;        String Username,password;        Username = Login.getusername ();        Password = Login.getpassword ();        if (username! = null && "Asdf". Equals (username))            if (password! = null && "123". Equals (password)) C12/>status = true;        Listener.loginstatus (status);}    }

3.View layer

An interface that abstracts some columns from the view layer for control operations

Public interface LoginView {public    String getusername ();    Public String GetPassword ();    public void Clearusername ();    public void Clearpassword ();    public void ShowMsg (String msg);

to implement the control operation of the interface within the activity, and initialize the presenter, it is possible to see that there is no logical processing in the activity , just the data or behavior of the control of the UI, All actions are implemented with presenter interfaces, so that the volume of activity is greatly reduced in the project.

public class Loginactivity extends Activity implements loginview{private EditText username, password;    Private Button login, clear;    Private Loginpresenter Loginpresenter;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_login);    Init ();        } private void Init () {loginpresenter = new Loginpresenterimpl (this);        Username = (EditText) Findviewbyid (r.id.username);        Password = (EditText) Findviewbyid (R.id.pass);        Login = (Button) Findviewbyid (R.id.login);        Clear = (Button) Findviewbyid (r.id.clear);                Login.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {            Loginpresenter.login ();        }        });                Clear.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) { Loginpresenter.clear();    }        });    } @Override Public String GetUserName () {return Username.gettext (). toString ();    } @Override Public String GetPassword () {return Password.gettext (). toString ();    } @Override public void Clearusername () {Username.settext ("");    } @Override public void Clearpassword () {Password.settext ("");    } @Override public void ShowMsg (String msg) {Toast.maketext (this, MSG, Toast.length_long). Show (); }}

4.Presenter layer

In the presenter layer, presenter master the view and model of all the interface, presenter can be based on different business logic through the MV two layer interface to achieve specific functions, let M and V independent out.

public class Loginpresenterimpl implements Loginpresenter, onloginlistener{    private userbiz userbiz;    Private LoginView LoginView;    Public Loginpresenterimpl (LoginView LoginView) {        this.loginview = LoginView;        userbiz = new Usrbizimpl (this);    }    @Override public    void Login () {        UserBean login = new UserBean ();        Login.setusername (Loginview.getusername ());        Login.setpassword (Loginview.getpassword ());        Userbiz.login (login);    }    @Override public    void Clear () {        loginview.clearpassword ();        Loginview.clearusername ();    }    @Override public    void LoginStatus (Boolean status) {        String msg;        if (status)            msg = "Login Succeed";        else            msg = "Login Failed";        Loginview.showmsg (msg);}    }

5.Demo

CSDN Download


Three. Summary

Simple to use the next MVP, but also discussed with friends, a lot of people say this looks pretty good, but it is very troublesome. Indeed now the Android project with MVP is not the majority, with some doubts landlord want to know what the Android native program is used in what style, and have seen some of the Android source code, but are intermittent, but also for a long time did not write a blog, the spirit of the love of technology, Plan to re-open the Android source code plan (from Android native System program to the framework again all the way down), now want to be able to persist, and output a series of blog to share and grow together.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A brief talk on the Android design mode MVP

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.