How to use the MVP architecture Android app Project

Source: Internet
Author: User

Catalogue
  1. About MVP
  2. MVP structure
  3. The difference between MVP and MVC
  4. Combat Drills

Body

1. Introduction to MVP

I believe that you are familiar with MVC: m-model-model, v-view-view, c-controller-Controller, MVP as an evolutionary version of MVC, then the equivalent of a similar MVP of the meaning: m-model-model, v-view-view, The p-presenter-represents the device. From the combination of MVC and MVP, Controlller/presenter plays the role of logical control in MVC/MVP, and plays a role in controlling the business processes. The most different of the MVP and MVC is that M and V are not directly related to the model and view does not have a direct relationship between the two is the presenter layer, which is responsible for regulating the indirect interaction between the view and the model, the MVP structure is shown below, For this diagram to understand can not be limited to the rules, after all, in different scenarios how much will be some. One of the important things about Android is that the UI operation basically needs to be done asynchronously, that is, to manipulate the UI in Mainthread, so it is reasonable to separate the view from the model. In addition, the interaction of presenter with view and model can further achieve loose coupling by using interface definition interaction and can be more convenient for unit testing through interfaces.

(Cite this article: mvp/in Http://zhengxiaopeng.com/2015/02/06/Android)

2. MVP Structure

View View is typically an activity, fragment implementation, and the view contains one or more presenter references to satisfy the business logic of the view. The interaction between view and presenter is bidirectional, that is, the view layer can call presenter's logical method, and presenter can also control the display of the view. Presenter Presenter, a bridge between model and view, is responsible for getting data from model to process and returning to view. But presenter and the other two layers of communication are through the interface protocol, so each presenter usually contain one or more interface protocols. Model, like MVC, is only responsible for processing app data as a data warehouse. An example of the Android development MVP model practice divides the app into the following four tiers.

The business class in Entities:app. Use Cases: responsible for processing and packaging the data from the entities. Presenters: Get the processed data from use cases and then provide the appropriate data for the UI based on the requirements logic. UI: Get processed final data from presenters and interact directly with the user. The principle of this four-layer design is that code calls can only be extended from the outer circle to the inner circle, the inner circle can not intervene and do not need to care about the function logic of the outer Circle, which is in line with the idea of MVP, use cases and presenters separate entities and UI intervals, So that the entities and UI only care about their own logic, data processing is completely handed over to the other two layers. Here, some students may have doubts, said the presenters why there is use cases out of the spoiler? In fact, this is also my choice of this project as an example of the purpose, read a lot of MVP articles, are talking about how presenter through the interface protocol and the other two layers of interaction, but mostly ignored the presenter layer of its own architecture, because only to apply the MVP model, Although the coupling degree of view is reduced to some extent, because presenter both process data and control UI interaction in combination with demand, there is a good chance that presenter logic will be redundant. The following example project wraps the use Cases between the presenter and the model, handing the data logic to usecases so that presenter is more focused on UI interaction.

(Cite this article: http://blog.csdn.net/guxiao1201/article/details/40147209)

3. The difference between MVP and MVC

After modifying the code of the original MVC pattern to MVP mode, we summarize the differences between the two patterns in the actual use process, which is basically summed up as two points: communication between layers through interface protocol; View and model no longer interact directly;

(For details, refer to MVC or MVP pattern-whats the difference?)

4. Practical Exercises

Simulate the login function to achieve the MVP architecture mode. Here are the practical steps

NO1, new View public part interface:

/** * Created by Bluesky on 2015/8/27. * MVP中V层的公共接口 */public interface IView {public void showProgressPar();public void hideProgressPar();public void showError(Object o);}

View inherits public iview interface

/** * Created by Bluesky on 2015/8/27. * 登录View接口 */public interface ILogin extends IView { public void showSuccess(Object o);}

The implementation of NO2 and view. The activity implements the Ilogin interface:

/** * Login page Activity */public class Mainactivity extends activity implements Ilogin {private Loginpresenter Mpresenter;priva Te User muser;private progressdialog mdialog; @Overrideprotected void OnCreate (Bundle savedinstancestate) {Super.oncrea    Te (savedinstancestate);    Setcontentview (R.layout.activity_main);    Mpresenter = new Loginpresenter (this);    Muser = new User (); Initview ();}    private void Initview () {final EditText pwd = (EditText) Findviewbyid (R.ID.PWD);    Final EditText name = (EditText) Findviewbyid (r.id.name);    Button loginbtn= (button) Findviewbyid (R.ID.LOGIN_BTN);            Loginbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {            Muser.setname (Name.gettext (). toString ());            Muser.setpassword (Pwd.gettext (). toString ());        Mpresenter.login (Muser); }    });} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it I s preSent.    Getmenuinflater (). Inflate (R.menu.menu_main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent Activit    Y in Androidmanifest.xml.    int id = item.getitemid ();    Noinspection simplifiableifstatement if (id = = r.id.action_settings) {return true; } return super.onoptionsitemselected (item);}   @Overridepublic void showsuccess (Object o) {user user= (user) O; Toast.maketext (This, "Login success Information:" +user.getname () + "/" +user.getpassword (), Toast.length_long). Show ();    @Overridepublic void Showprogresspar () {mdialog = new ProgressDialog (mainactivity.this);    Mdialog.setmessage ("Loading ..."); Mdialog.show ();} @Overridepublic void Hideprogresspar () {mdialog.hide ();} @Overridepublic void ShowError (Object o) {toast.maketext (This, "Exception:" + ((Exception) O). GetMessage (), Toast.length_long) .Show ();}} 

activity XML layout:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:o rientation= "vertical" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/ Activity_horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/ Activity_vertical_margin "tools:context=". Mainactivity "><textviewandroid:layout_width=" match_parent "android:layout_height=" Wrap_content "Android: text= "@string/hello_world"/><edittextandroid:id= "@+id/name" android:layout_width= "Match_parent" Android: layout_height= "wrap_content" android:hint= "Please enter user name"/><edittextandroid:id= "@+id/pwd" android:layout_width= " Match_parent "android:layout_height=" wrap_content "android:hint=" Please enter the password "/><buttonandroid:id=" @+id/login_btn "Android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:text=" Login "/&Gt;</linearlayout> 

No3, New Loginpresenter. We are programming for interfaces, so there is no way to create a new presenter interface in the demo, which is for extensibility considerations. Presenter Interface

/** * Created by Bluesky on 2015/8/27. * MVP中P层 */public interface Presenter {}

Login presenter Implement presenter interface, where the view and model layer Bridge connection, business scheduling, play a commanding role

/** * Created by BlueSky on 2015/8/27. */public class Loginpresenter implements Presenter {private Ilogin mloginview;private iloginbiz mloginbiz;private    Handler Mhandler = new Handler ();p ublic loginpresenter (Ilogin mloginview) {this.mloginview = Mloginview; this.mloginbiz = new Loginbizimpl ();}    /** * Login * * @param o */public void login (Object o) {mloginview.showprogresspar (); Mloginbiz.login (O, New Listener () {@Override public void complete () {Mhandler.post (new Runnable                () {@Override public void run () {mloginview.hideprogresspar ();        }            });                } @Override public void onsuccess (Final Object o) {mhandler.post (new Runnable () {                @Override public void Run () {mloginview.showsuccess (o);        }            }); } @Override public void onfailed (final Exception e) {mHandler.post (New Runnable () {@Override public void run () {mloginview.sh                Owerror (e);        }            }); }    });}}

No4, model layer for business logic processing. New model layer interface, then implement business logic processing, asynchronous processing and sub-threading and main thread communication. Model interface:

/** * Created by Bluesky on 2015/8/27. */public interface ILoginBiz {public void login(Object o,Listener listener);}

Model implementation:

/** * Created by BlueSky on 2015/8/27. */public class Loginbizimpl implements iloginbiz {@Overridepublic void login (Object o, Final Listener Listener) {final use R user = (user) o;new Thread (new Runnable () {@Overridepublic void run () {try {thread.sleep (2 *);} catch (Interruptede Xception e) {e.printstacktrace ();} Listener.complete (), if (User.getname (). Equals (User.getpassword ())) {//Success listener.onsuccess (user);} else {// Failed listener.onfailed (new Exception ("Run exception ..."));}}). Start ();}}  

Entity class:

/** * Created by Bluesky on 2015/8/27. */public class User implements Serializable {private String name;private String password;public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

Callback Interface:

/** * Created by Bluesky on 2015/8/27. */public interface Listener {public void complete();public void onSuccess(Object o);public void onFailed(Exception e);}

Source

Https://github.com/hrx3627/MVPAndroidDemo

Reference information

http://www.imooc.com/wenda/detail/216700http://www.cnblogs.com/daizhj/archive/2009/04/30/1447035.HTMLhttp:// The mvp/http://in Blog.csdn.net/lmj623565791/article/details/46596109http://zhengxiaopeng.com/2015/02/06/android blog.csdn.net/guxiao1201/article/details/40147209

Personal Information
  • : huangrx1988
  • Blog: http://blog.csdn.net/hrx3627
  • github:https://github.com/hrx3627
  • Android Chat QQ Group: 367818514
  • qq:1084986314

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

How to use the MVP architecture Android app Project

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.