Summary of MVP for Android Framework Patterns
Android Framework Model MVC and MVP, which have been summarized before, are seldom used in the development, and little attention has been paid to them. Many codes are written at will, but now the development requirements follow the MVP design pattern, so I want to make a summary of MVP framework design and design a Demo program to help. We better understand MVP, straighten out the design ideas of MVP, it is important to learn to use MVP.
I don't want to talk about the comparison between MVC mode and MVP mode. Nowadays, few people use MVC mode once they use MVP.
A previous summary of knowledge about MVP and MVC framework patterns:
http://blog.csdn.net/wenzhi20102321/article/details/53302453
I. Basic Understanding of MVP Framework Design Patterns
(1) Basic concepts
MVP is the abbreviation of Model, View and Presenter, representing three different modules in the project.
Model: Responsible for data loading or storage, such as data acquisition from network or local database, etc.
View: Responsible for displaying interface data and interacting with users;
Presenter: The equivalent of a coordinator is the bridge between the model and the view, separating the model from the view.
MPV has evolved from the classical MVC model, and its basic ideas are interlinked. M is the model model model, providing business data; P and C in M VC play similar roles, Presenter moderator, carrying out logical processing. V is a View view that displays page operations.
There is a major difference between MVP and MVC:
View doesn't use Model directly in MVP. The communication between them is through Presenter. All interactions take place inside Presenter class. It can be found in code that Presenter class has both View object and Model object, but there is no Model object in Activity. It uses Pre. Senter object to invoke Model object; Activity is to have View object and Presenter object, how does Presenter object come? This is to be created in the construction method. How does the View object come about? Actually, Activity implements the View, which is relative to the View object and needs to rewrite the method of the View interface! Another important thing is to use this Presenter to bind Activity (actually to bind the View interface). In this way, after Presenter processes the data with the model, Presenter calls the method of View interface to realize the operation of the page.
The above paragraph is also the key theory of MVP framework pattern and needs to be understood thoroughly. You can also learn from my code in detail, we must make clear the relationship between them! ____________
As shown in the figure below, View and Model do not interact directly, but use Presenter as a bridge between View and Model. The Presenter layer also holds references to the Interface of the Viwe layer and the Model layer, while the View layer holds references to the Presenter layer Interface. When some Interface of the View layer needs to display some data, it first calls some Interface of the Presenter layer, then the Presenter layer calls the Model layer to request data. When the Model layer data is loaded successfully, it calls the callback method of the Presenter layer to inform the Presenter layer that the data is loaded, and finally the Presenter layer calls the View layer again. The Interface displays the loaded data to the user. This is the whole core process of MVP mode.
The advantage of this layering is that it greatly reduces the coupling between the Model and View layers. On the one hand, View layer and Model layer can be developed and tested independently, and they are independent of each other. On the other hand, Model layer can encapsulate and reuse, which can greatly reduce the amount of code. Of course, MVP has some other advantages, which are not discussed here.
(2) Design of MVP Framework Model in Development
1. In general, MVP design is to create a new package name of mvp, in which the model, view and presenter package names are built respectively. The activity and fragment of the package name ui of MVP and page are separated.
As shown in the figure:
Although MVP is for page logic, MVP looks ugly under the activity package name.
Note: I also had this question before: are not both view and ui view packages?
In fact, the package of View in MVP is not a view class like activity, but an operation of activity view class. For example, under this login activity, there will be the need to get user's account, password, click login and so on, which requires defining the parties of these operations. Actually, the view package defines the interface class. The methods in the view package are all abstract methods. Define the operation needed by the page, and the implementation of the specific content of the page should be in Activity.
2. File design under MVP package
(1) Classes under the package name of model
Designing the logic of data processing, we usually design an internal interface class to allow the presenter object to set up listeners and get data. Because a lot of data processing needs sub-threads, data can not be returned immediately.
(2) Classes under view package name
The logic needed in the design view is the interface method, which is also the interface class. This interface class also needs a fixed Activity page to implement, and rewrite the method inside. The operation of writing pages in the method is controlled by Presenter object. Generally, the method callbacks are judged after data or logic processing.
(3) Classes under presenter package name
Designing interaction between activity and model requires both View objects and model objects.
Logical operations related to data are thrown to Presenter in Activity, and View is only responsible for handling user interface operations. After the Presenter calls Model to process the data, it updates the information displayed by View through the View interface method.
Second, let's look at the use of MVP mode in specific projects.
Below is the design of a login page procedures, to introduce you in detail the design process.
The interface is as follows:
Click on the login and verify the success before jumping to the user interface.
(1) Detailed design process and ideas
1. Write the layout page first. This should be the simplest one. Two EditText s and one button will do.
2. Designing user's base class User, setting the get and set methods of user name and password.
3. Design the View interface class LoginView in mvp, which defines five methods: obtaining user's account, obtaining user's password, login, displaying network anomalies, login verification errors.
Code:
/**
* mvp Definition of View in
* Definition of User's Operational Behavior in User Login Interface
*/
public interface LoginView {
String getAccount();//Get the user's account and return it
String getPassword();//Get the user's Moma and return the password
void loginSuccess(User user);//The implementation of login needs to pass in user objects
void showNetworkError();//Display network anomalies
void showVerifyFailed();//Information validation failed, account or password incorrect
}
4. Design the model class LoginModel in mvp, which needs to verify that the user's account and password are correct. And create an internal interface to allow data processing to complete the return time, because the general network data is completed in the sub-thread, can not immediately return data.
Code:
/**
* MVP model Data Processing Class in
* Here, the data at logon time is processed
*/
public class LoginModel {
/**
* Processing login business and returning results
*/
public void login(String name,String password,OnLoginResultListener onLoginResultListener){
//Generally, logins are request servers, validation
//Here's a little simpler. Don't mind.
if ("liwen".equals(name)&&"123456".equals(password)){
onLoginResultListener.loginSuccess(new User(name,password));//Log in successfully and return the user object to him
}else {
onLoginResultListener.loginFailure();//Logon failure
}
}
//Callback interface
public interface OnLoginResultListener {
void loginSuccess(User user);//Callback method after successful login, returning the User object
void loginFailure();//Method of Return after Logon Failure
}
5. Design the Presenter class LoginPresenter in mvp, realize the exchange of View and Model, and focus on understanding.
/**
* mvp Design in Presenter
* It's also a difficult one to understand.
* presenter It's the moderator, the intermediary between view and model.
* You need both View objects and Model objects! The general approach is to create a model object in the constructor and create a method-bound View interface
* Here you can find that after data processing or logical judgment, all the operations are done for the View object in mvp.
*/
public class LoginPresenter {
/**
* Login business implementer, data processing operator
*/
private LoginModel mLoginModel;
/**
* Instantiating model Objects in Construction Method
*/
public LoginPresenter() {
mLoginModel = new LoginModel();
}
//View Interface Object
private LoginView mLoginView;
/**
* Method of Binding View
*
* @param loginView
*/
public void bind(MyActivity loginView) {
mLoginView = loginView;
}
/**
* Login business
*/
public void login() {
String account = mLoginView.getAccount();
String password = mLoginView.getPassword();
Log.e("TAG", "account:" + account + ",password" + password);
if (checkParameter(account, password)) {
doSomePrepare();
//Login, data needs to be processed, all to be executed in the model
mLoginModel.login(account, password, new LoginModel.OnLoginResultListener() {
//Callback method for successful login
@Override
public void loginSuccess(User user) {
mLoginView.loginSuccess(user); //Return the User object to the view page
}
//Callback method for login failure
@Override
public void loginFailure() {
mLoginView.showVerifyFailed();//Returns the result of validation failure to the view page
}
});
}
}
/**
* Do some preparation
*/
private void doSomePrepare() {
//Here you can set the button not to click! Otherwise, it's not good to click on login all the time.
}
/**
* Check whether the parameter is empty~~~
*
* @param account
* @param password
* @return
*/
private boolean checkParameter(String account, String password) {
if (TextUtils.isEmpty(account) | TextUtils.isEmpty(password)) {
mLoginView.showVerifyFailed();//Error prompting
return false;
} else if (!checkNetwork()) {
mLoginView.showNetworkError();//Hint for network errors
return false;
}
return true;
}
/**
* Detection of network availability
*/
public boolean checkNetwork() {
return true;//First display can be networked, in practice to use code to judge
}
}
Some of the above methods may not be written, such as checking the network or doing some preparations, but in the actual process, it is necessary to make a lot of judgments, here is a few casual verbose sentences.
6. The following is Activity, which is a little more difficult and needs to be understood.
/**
* Activeness of the login program example
* Here we need to create presenter object, presenter object has view object and model object!
*/
public class MyActivity extends Activity implements LoginView, View.OnClickListener {
private EditText et_name;
private EditText et_password;
private Button btn_logon;
private LoginPresenter loginPresenter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
/**
* Initialization data
*/
private void initView() {
et_name = (EditText) findViewById(R.id.et_name);
et_password = (EditText) findViewById(R.id.et_password);
btn_logon = (Button) findViewById(R.id.btn_login);
btn_logon.setOnClickListener(this);
loginPresenter = new LoginPresenter();
loginPresenter.bind(this);//Bind View and Presenter, because the Activity has implemented the interface and already contains View objects
}
/**
* Listening Method of Logon Button
* Presenter is needed to process background data.
*/
@Override
public void onClick(View v) {
loginPresenter.login();
}
/**
* Here are five ways to implement LoginView
*/
@Override
public String getAccount() {
return et_name.getText().toString();
}
@Override
public String getPassword() {
return et_password.getText().toString();
}
@Override
public void loginSuccess(User user) {
//After successful login, page Jump is usually achieved.
Toast.makeText(this, "Successful login", Toast.LENGTH_SHORT).show();
}
@Override
public void showNetworkError() {
Toast.makeText(this, "Current network unavailability", Toast.LENGTH_SHORT).show();
}
@Override
public void showVerifyFailed() {
Toast.makeText(this, "Mistyped username or password", Toast.LENGTH_SHORT).show();
}
}
As you can see above, the loginPresenter object is created at initialization, and the loginModel object is also created in the construction method of loginPresenter. Activity implements LoginView, which is equivalent to having LoginView object. It only needs to bind LoginView with loginPresenter, then MVP model, view, prese. The three inters have been instantiated and linked together.
The statement loginPresenter binds LoginView is: loginPresenter.bind(this); bind Avtivity, also bind View! The methods calling LoginView in loginPresenter are executed in Activity.
Display after program running:
The following is the download address of the source code:
http://download.csdn.net/detail/wenzhi20102321/9803842
(2) Understanding and other knowledge of MVP
In fact, the above is already a standard program of MVP framework mode, but it is the simplest one, and the general program needs to make more judgments. For example, judge the account number, the password is empty, and so on.
In the actual use of MVP mode, you need not only to create a View, Presenter or Model, but also to create three Base classes (BaseView is the interface) so that each View, Pressenter or Model inherits the Base class, and the Base class does some common operations, such as:BasePresenter You can write a way to bind View, because every Presenter must bind View, and BaseView can do some things that every page needs: show animation, hide animation, show network anomalies, and so on. In a word, design according to the actual needs of the program.
Others may wonder if using MVP is troublesome, and how much work it would take to design model s, presenter s, and view s for each page if using MVP is not enough.
Here I also briefly explain my understanding:
In fact, the use of MVP is to reduce the coupling of programs and make the logic clearer; not all Activity pages are to use MVP, generally involving more data processing, such as login interface, registration interface is required MVP framework mode, and those simple pages, such as only showing simple numbers. Activities that attempt or display a control do not need MVP to complete. They can be designed according to normal logic.
When MVP is introduced here, I think many people can understand it. If you don't understand it, you can download the source code and experience it slowly. At the same time, you can write a registration page to practice some, and you will have a clear idea. You can also leave a message for discussion.
Co-encouragement: Live in the Present