Reprint please indicate the source:
http://blog.csdn.net/lmj623565791/article/details/46596109;
This article is from: "Zhang Hongyang's Blog"
I. Overview
For MVP (Model View Presenter), most people can say one or two: "Evolutionary version of MVC", "Make Model and View fully decoupled" and so on. This blog post is just for the record, to make some comments, and to help you write code for the MVP style for an activity page.
For MVP, there is a problem in my heart:
Why should this model be accepted by the vast majority of Android programmers?
Asked some programmers, their general understanding of MVP is: "The code is clear, but there are many classes added." The first time I saw the MVP, I saw a demo, after reading it feels very nice (but back, I think of an example to write, the headache can not be written out, of course, this will be said later in the article). The reason for Nice is because it does make the clarity of the code a great boost.
So, Ascension is generally compared, and in retrospect, there is no code structure to apply MVP. Many people say it's obviously MVC:
- View: Corresponds to a layout file
- Model: Business logic and entity model
- Controllor: Corresponds to activity
It does look like that, but think about it. The view corresponds to the layout file, in fact, there are very few things to do, in fact, about the data binding in the layout file operation, the event handling code is in the activity, It causes the activity to be both a view and a controller (Data-binder, of course, might make the view look more like a view). This may be why, in this article, there is one sentence:
Most of the modern Android applications just use View-model architecture,everything are connected with Activity.
When the schema is changed to MVP, presenter's appearance, actvity as the view layer, presenter is responsible for the completion of the view layer and the model layer of interaction. Now this is the case:
- View corresponds to activity, which is responsible for drawing the view and interacting with the user
- Model is still business logic and entity model
- Presenter is responsible for the interaction between view and model
OK, the first simple to understand, the text will have an example of the time can be intuitive to feel under.
Small summary, that is, the reason is refreshing, because the jump is from 并不标准的MVC
MVP
a change, reducing the activity of the responsibility, simplifying the activity of the code, the complex logic code extracted into the presenter for processing. The corresponding benefit is that the coupling degree is lower and more convenient to test. To borrow two pictures (from: This article), representing the above transformations:
Change to:
Second, the difference between MVP and MVC
OK, it says a bunch of theories, and here's a look at the difference between MVC and MVP, see (from: This article):
In fact, the most obvious difference is that MVC allows model and view to interact, and the MVP is clearly the interaction between model and view is done by presenter. Another point is that the interaction between the presenter and the view is through the interface (which is reflected in the code).
There are a bunch of conceptual things, as well as the advantages of a little, interested in self-Baidu. Here are some simple requirements to show how to write the MVP demo.
Third, simple Login Demo
:
To see this effect, first look at the project structure after completion:
OK, let's start with a step-by-step approach to writing.
(a) Model
First the entity class user does not have to consider this certainly has, second from can see at least one business method login (), these two points is not difficult, we first complete:
PackageCom.zhy.blogcodes.mvp.bean;/** * Created by Zhy on 15/6/18. * * Public class User{ PrivateString username;PrivateString password; PublicStringGetUserName() {returnUsername } Public void Setusername(String username) { This. Username = Username; } PublicStringGetPassword() {returnPassword } Public void SetPassword(String password) { This. Password = password; }}
package com.zhy.blogcodes.mvp.biz;/** * Created by zhy on 15/6/19. */publicinterface IUserBiz{ publicvoidlogin(String username, String password, OnLoginListener loginListener);}
Packagecom.zhy.blogcodes.mvp.biz;ImportCom.zhy.blogcodes.mvp.bean.User;/** * Created by Zhy on 15/6/19. * * Public class userbiz implements iuserbiz{ @Override Public void Login(FinalString username,FinalString Password,FinalOnloginlistener Loginlistener) {//Simulate child thread time consuming operation NewThread () {@Override Public void Run() {Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }//Demo Login Successful if("Zhy". Equals (username) &&"123". Equals (password)) {User user =NewUser (); User.setusername (username); User.setpassword (password); loginlistener.loginsuccess (user); }Else{loginlistener.loginfailed (); }}}.start (); }}
package com.zhy.blogcodes.mvp.biz;import com.zhy.blogcodes.mvp.bean.User;/** * Created by zhy on 15/6/19. */publicinterface OnLoginListener{ void loginSuccess(User user); void loginFailed();}
Entity class Needless to say, as for the business class, we have extracted an interface, an implementation class which is also very common ~~login method, is usually connected to the server, is a time-consuming operation, so we opened up a sub-thread, Thread.Sleep (2000) simulated time-consuming, because it is time-consuming operation, So we use a callback interface to notify the state of the login.
In fact, this is still relatively good writing, because it is not different from the traditional wording.
(ii) View
As we said above, presenter and view interactions are through interfaces. So here we need to define one ILoginView
, the difficulty lies in what should be the method, we take a look at:
Can see we have two buttons, one is login, the other is clear;
Login indicates that you want to have a user name, password, then the corresponding two methods:
String getUserName(); String getPassword();
Moreover login is a time-consuming operation, we need to give the user a friendly hint, generally is Operation ProgressBar, so again two:
void showLoading(); void hideLoading();
Login Of course there is login success and failure processing, we mainly see success we are jump activity, and failure may be to give a reminder:
void toMainActivity(User user); void showFailedError();
Ok,login This method we have finished analysis ~ ~ There is a clear that is simple:
void clearUserName(); void clearPassword();
Fully integrated, the interface is:
package com.zhy.blogcodes.mvp.view;import com.zhy.blogcodes.mvp.bean.User;/** * Created by zhy on 15/6/19. */publicinterface IUserLoginView{ String getUserName(); String getPassword(); void clearUserName(); void clearPassword(); void showLoading(); void hideLoading(); void toMainActivity(User user); void showFailedError();}
With the interface, the implementation is too good to write ~ ~ ~
In summary, for the view interface, to observe the function of the operation, and then consider:
- What does the operation require? (GetUserName, GetPassword)
- The results of the operation, corresponding feedback? (Tomainactivity, Showfailederror)
- The corresponding friendly interaction during the operation? (Showloading, hideloading)
The following is the implementation of our view of the class, ha, in fact, is activity, the article began to say that the MVP of the view is actually activity.
PackageCOM.ZHY.BLOGCODES.MVP;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.Toast;ImportCOM.ZHY.BLOGCODES.R;ImportCom.zhy.blogcodes.mvp.bean.User;ImportCom.zhy.blogcodes.mvp.presenter.UserLoginPresenter;ImportCom.zhy.blogcodes.mvp.view.IUserLoginView; Public class userloginactivity extends actionbaractivity implements Iuserloginview { PrivateEditText Metusername, Metpassword;PrivateButton Mbtnlogin, Mbtnclear;PrivateProgressBar mpbloading;PrivateUserloginpresenter Muserloginpresenter =NewUserloginpresenter ( This);@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_user_login); Initviews (); }Private void initviews() {metusername = (EditText) Findviewbyid (r.id.id_et_username); Metpassword = (EditText) Findviewbyid (R.id.id_et_password); Mbtnclear = (Button) Findviewbyid (r.id.id_btn_clear); Mbtnlogin = (Button) Findviewbyid (R.id.id_btn_login); mpbloading = (ProgressBar) Findviewbyid (r.id.id_pb_loading); Mbtnlogin.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {Muserloginpresenter.login (); } }); Mbtnclear.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {muserloginpresenter.clear (); } }); }@Override PublicStringGetUserName() {returnMetusername.gettext (). toString (); }@Override PublicStringGetPassword() {returnMetpassword.gettext (). toString (); }@Override Public void Clearusername() {Metusername.settext (""); }@Override Public void Clearpassword() {Metpassword.settext (""); }@Override Public void showloading() {mpbloading.setvisibility (view.visible); }@Override Public void hideloading() {mpbloading.setvisibility (view.gone); }@Override Public void tomainactivity(User user) {Toast.maketext ( This, User.getusername () +"Login success, to Mainactivity", Toast.length_short). Show (); }@Override Public void Showfailederror() {Toast.maketext ( This,"Login Failed", Toast.length_short). Show (); }}
It is an easy task to implement the interface we defined above in activity, after all, the interface guides us to complete it.
Finally, look at our presenter.
(c) Presenter
Presenter is used as a bridge between model and view, what should be the method?
In fact, it is also mainly to see what the operation of the function, such as this example, two operations: Login and clear.
PackageCom.zhy.blogcodes.mvp.presenter;ImportAndroid.os.Handler;ImportCom.zhy.blogcodes.mvp.bean.User;ImportCom.zhy.blogcodes.mvp.biz.IUserBiz;ImportCom.zhy.blogcodes.mvp.biz.OnLoginListener;ImportCom.zhy.blogcodes.mvp.biz.UserBiz;ImportCom.zhy.blogcodes.mvp.view.IUserLoginView;/** * Created by Zhy on 15/6/19. * * Public class userloginpresenter{ PrivateIuserbiz userbiz;PrivateIuserloginview Userloginview;PrivateHandler Mhandler =NewHandler (); Public Userloginpresenter(Iuserloginview Userloginview) { This. Userloginview = Userloginview; This. userbiz =NewUserbiz (); } Public void Login() {userloginview.showloading (); Userbiz.login (Userloginview.getusername (), Userloginview.getpassword (),NewOnloginlistener () {@Override Public void loginsuccess(FinalUser user) {//needs to be executed on the UI threadMhandler.post (NewRunnable () {@Override Public void Run() {userloginview.tomainactivity (user); Userloginview.hideloading (); } }); }@Override Public void loginfailed() {//needs to be executed on the UI threadMhandler.post (NewRunnable () {@Override Public void Run() {userloginview.showfailederror (); Userloginview.hideloading (); } }); } }); } Public void Clear() {userloginview.clearusername (); Userloginview.clearpassword (); }}
Note that the above code, our presenter complete the interaction between the two, then definitely need the implementation of the two classes. It's about getting the required parameters from the view, giving the model a way to execute the business method, the feedback needed during the execution, and the results, and then the view to do the corresponding display.
OK, get an example after the decomposition of the above basic can be completed. The above is purely personal opinion, welcome to discuss and spit groove ~ has a nice day ~.
SOURCE Click to download
Public Number: Hongyangandroid
(Welcome attention, the first time to push the blog post information)
Resources
- Https://github.com/zhengxiaopeng/Rocko-Android-Demos/tree/master/android-mvp
- Https://github.com/antoniolg/androidmvp
- Https://github.com/pedrovgs/EffectiveAndroidUI
- http://zhengxiaopeng.com/2015/02/06/Android%E4%B8%AD%E7%9A%84MVP/
- Http://magenic.com/Blog/Post/6/An-MVP-Pattern-for-Android
- Http://antonioleiva.com/mvp-android/
- Http://konmik.github.io/introduction-to-model-view-presenter-on-android.html
Talking about MVP in Android